Skip to content

Instantly share code, notes, and snippets.

@timc1
Created January 28, 2019 17:41
Show Gist options
  • Save timc1/fddf528447ae9cdb8f7998e2667e17cf to your computer and use it in GitHub Desktop.
Save timc1/fddf528447ae9cdb8f7998e2667e17cf to your computer and use it in GitHub Desktop.
A React hook to trigger callback function once a DOM element is in view.
import { useEffect, useRef } from 'react'
const isElementInView = (el: HTMLElement) => {
const { top, bottom } = el.getBoundingClientRect()
// Add an offset so item doesn't load the moment a tiny part of the element is showing.
if (top < window.innerHeight - 125 && bottom > 125) {
return true
}
return false
}
const useScrollAnimation = (domRef: any, cb: () => any) => {
const eventHandler = useRef(() => {
if (Array.isArray(domRef)) {
for (let ref of domRef) {
if (isElementInView(ref.current)) {
cb()
window.removeEventListener('scroll', eventHandler.current)
break
}
}
} else if (isElementInView(domRef.current)) {
cb()
window.removeEventListener('scroll', eventHandler.current)
}
})
useEffect(() => {
window.addEventListener('scroll', eventHandler.current)
// Call on first load
eventHandler.current()
return () => window.removeEventListener('scroll', eventHandler.current)
}, [])
}
export default useScrollAnimation
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment