Skip to content

Instantly share code, notes, and snippets.

@zackify
Last active January 30, 2019 01:31
Show Gist options
  • Star 2 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save zackify/47f6fba5fcf0c01bea60224f0cc30d4f to your computer and use it in GitHub Desktop.
Save zackify/47f6fba5fcf0c01bea60224f0cc30d4f to your computer and use it in GitHub Desktop.
React hook that triggers one time, when an element becomes visible on the screen
//Copied from SO checking if an element is in view
const checkIfInView = (elementPosition, extraOffset) =>
elementPosition.top >= 0 &&
elementPosition.left >= 0 &&
elementPosition.bottom + extraOffset <=
(window.innerHeight || document.documentElement.clientHeight) &&
elementPosition.right + extraOffset <=
(window.innerWidth || document.documentElement.clientWidth);
//React hook that sets state when in view
const useEnteringView = (extraOffset = 0) => {
const [isEntering, setIsEntering] = useState(false);
const ref = useRef(null);
const handleScroll = () => {
if (!ref.current || isEntering) return;
let elementPosition = ref.current.getBoundingClientRect();
let isInView = checkIfInView(elementPosition, extraOffset);
if (isInView && !isEntering) setIsEntering(true);
};
useEffect(() => {
//Yes this should get debounced :)
window.addEventListener('scroll', handleScroll);
return () => window.removeEventListener('scroll', handleScroll);
});
return { isEntering, ref };
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment