I have a list of sections inside of a container (root), each one observed by the same Intersection Observer.
When clicking an anchor on the left-nav (red), it scrolls to that section and the intersection observer callback updates the state with the correspondent section ID. In short, I'm trying to dynamically style the anchor while scrolling and navigating recording the ID and comparing it to the href attribute.
It works as expected as long as only one section respects the threshold, but sometimes I face this situation:
When scrolling to top (e.g. from 4 clicking to 2), it works as expected, the last state ID corresponds to the href attribute I just clicked.
But when I scroll down (e.g. from 1 clicking to 2), since 2, 3 and 4 are visible, the last section ID set in the state corresponds to the section #4.
Is there any way to target always the nearest entry to the root?
export const Main = () => {
const sectionRefs = useRef([]);
const observerRef = useRef(null);
const [intersectionId, setIntersectionId] = useIntersection();
useEffect(() => {
const intersectionCallback = (entries) => {
entries.some((entry) => {
if (entry.isIntersecting) {
setIntersectionId(entry.target.id);
return true;
}
});
};
observerRef.current = new IntersectionObserver(intersectionCallback, {
root: document.getElementById('root'),
threshold: 0.75,
rootMargin: '0px 0px 0px 0px',
});
examplesRefs.current.forEach((sectionElement) => {
observerRef.current.observe(sectionElement);
});
return () => {
observerRef.current.disconnect();
};
}, [setIntersectionId]);
return (
<Container id="root">
{examples.map(({ id }, index) => (
<Section
key={id}
id={id}
ref={(child) => (sectionRefs.current[index] = child)}
/>
))}
</Container>
);
};