codesandbox example here: https://codesandbox.io/s/quirky-wozniak-3qih8p?file=/src/Progress.tsx
I am trying to use the Intersection Observer API to track both the first and last elements of my list. My goal is to display either a left or right button based on the horizontal scroll position. However, I have run into an issue where the intersection observer is only tracking the first element and I am unsure why this is happening and how to correct it.
From the docs, the IntersectionObserver callback is called with:
entries An array of IntersectionObserverEntry objects, each representing one threshold which was crossed, either becoming more or less visible than the percentage specified by that threshold.
So, you do not necessarily receive both [first, last]
elements in the callback – just those whose amount of intersection has changed.
As a rough cut you might use something like:
const observer = new IntersectionObserver(
entries => {
const lookup = new Map(entries.map(entry => [entry.target, entry.isIntersecting]));
setLeftVisible(!lookup.get(leftRef.current!));
setRightVisible(!lookup.get(rightRef.current!));
},
...
);