Skip to content

Instantly share code, notes, and snippets.

@danedavid
Created March 23, 2019 17:33
Show Gist options
  • Save danedavid/352f444e3942b301318b6600e9a238a8 to your computer and use it in GitHub Desktop.
Save danedavid/352f444e3942b301318b6600e9a238a8 to your computer and use it in GitHub Desktop.
import { useEffect } from 'react';
export const useActiveOnIntersect = (setActiveElement, elementRef) => {
const options = {
root: document.querySelector('#intersector'),
rootMargin: '0px',
threshold: 1.0,
};
const callback = (entries) => {
const entry = entries[0];
const {
intersectionRatio,
isIntersecting,
} = entry;
if ( isIntersecting && intersectionRatio > 0.95 ) {
setActiveElement();
}
};
useEffect(() => {
if ( elementRef.current ) {
const observer = new IntersectionObserver(callback, options);
observer.observe(elementRef.current);
}
}, []);
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment