-
-
Save maxpou/f235ef5b2e0f63b3a32e78f484b081c8 to your computer and use it in GitHub Desktop.
useIsInViewport - a React Hook to detect if an HTML element is visible on screen
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
// How to use it | |
export default function MyComponent(): JSX.Element { | |
const containerRef = useRef<HTMLDivElement>(null); | |
const isInViewport = useIsVisibleOnScreen(containerRef, '50px'); | |
return ( | |
<div ref={containerRef}> | |
<h1>{isInViewport ? 'Visible' : 'Not visible'}</h1> | |
</div> | |
); | |
} |
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 { MutableRefObject, useEffect, useMemo, useState } from 'react'; | |
export function useIsVisibleOnScreen( | |
ref: MutableRefObject<HTMLElement | null>, | |
rootMargin = '0px', | |
): boolean { | |
const [isVisible, setIsVisible] = useState(false); | |
const observer = useMemo( | |
() => | |
new IntersectionObserver( | |
([entry]) => setIsVisible(entry.isIntersecting), | |
{ rootMargin }, | |
), | |
[rootMargin], | |
); | |
useEffect(() => { | |
const currentElement = ref?.current; | |
if (currentElement) { | |
observer.observe(currentElement); | |
} | |
return () => { | |
observer.disconnect(); | |
}; | |
}, [ref, observer]); | |
return isVisible; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment