Created
September 14, 2022 05:32
-
-
Save hi-ogawa/b273d5f0a8dd39758e796dc6f885ee35 to your computer and use it in GitHub Desktop.
useIntersectionObserverEntry
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
| // const ref = useIntersectionObserverEntry(entry => console.log(entry)) | |
| // return <div ref={ref}>...</div> | |
| function useIntersectionObserverEntry( | |
| callback: (value?: IntersectionObserverEntry) => void | |
| ): React.RefCallback<Element> { | |
| const observerRef = React.useRef<IntersectionObserver>(); | |
| const callbackRef = React.useRef<typeof callback>(callback); | |
| callbackRef.current = callback; | |
| return React.useCallback(el => { | |
| if (el) { | |
| const observer = new IntersectionObserver(entries => { | |
| callbackRef.current(entries[0]); | |
| }); | |
| observer.observe(el); | |
| observerRef.current = observer; | |
| } else { | |
| callbackRef.current(undefined); | |
| observerRef.current?.disconnect(); | |
| } | |
| }, []); | |
| } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment