Created
April 16, 2021 17:20
-
-
Save pffigueiredo/8d0b342b300699fe3894afaf390277a1 to your computer and use it in GitHub Desktop.
React hook to check if some element is currently on the view port
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 { RefObject, useEffect, useState } from 'react'; | |
import throttle from 'utils/throttle'; | |
export default function useOnScreen( | |
elementRef: RefObject<HTMLElement> | |
): boolean { | |
const [isVisible, setIsVisible] = useState(false); | |
const onScroll = throttle(() => { | |
if (!elementRef.current) { | |
setIsVisible(false); | |
return; | |
} | |
const { top } = elementRef.current.getBoundingClientRect(); | |
setIsVisible(top >= 0 && top <= window.innerHeight); | |
}, 200); | |
useEffect(() => { | |
document.addEventListener('scroll', onScroll, true); | |
return () => document.removeEventListener('scroll', onScroll, true); | |
}); | |
return isVisible; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment