Last active
September 11, 2024 07:28
React hook check if element is in viewport
This file contains 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
import { useState, useEffect, RefObject, useCallback } from "react"; | |
function isElementInViewport(el: Element) { | |
var rect = el.getBoundingClientRect(); | |
return ( | |
rect.bottom >= 0 && | |
rect.right >= 0 && | |
rect.top <= (window.innerHeight || document.documentElement.clientHeight) && | |
rect.left <= (window.innerWidth || document.documentElement.clientWidth) | |
); | |
} | |
export function useInViewport(ref: RefObject<Element>) { | |
const [isVisible, setIsVisible] = useState(true); | |
const update = useCallback(() => { | |
if (ref.current) { | |
setIsVisible(isElementInViewport(ref.current)); | |
} | |
}, [ref]); | |
useEffect(() => { | |
["scroll", "load", "DOMContentLoaded", "resize", "click"].forEach(type => { | |
window.addEventListener(type, update); | |
}); | |
return () => { | |
["scroll", "load", "DOMContentLoaded", "resize", "click"].forEach(type => { | |
window.removeEventListener(type, update); | |
}); | |
}; | |
}, [update]); | |
return { isVisible, update }; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Nice. I'd suggest using
IntersectionObserver
though, as it's a bit more resource-friendly 🙂E.g. https://usehooks-ts.com/react-hook/use-intersection-observer