Last active
January 30, 2019 01:31
-
-
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
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
//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