Last active
September 3, 2019 20:22
-
-
Save itsMapleLeaf/362810b3de6c36320de6fa364da8cef1 to your computer and use it in GitHub Desktop.
useWindowIntersection
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
| function Example() { | |
| const elementRef = useRef<HTMLDivElement>(null) // ref for the element you want to watch | |
| const isInsideWindow = useWindowIntersection(elementRef) | |
| return <div ref={elementRef}> | |
| is inside window: {isInWindow} | |
| </div> | |
| } |
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
| import { useState, useEffect } from "react" | |
| export default function useWindowIntersection<E extends Element>( | |
| targetRef: React.RefObject<E>, | |
| ) { | |
| const [isInWindow, setIsInWindow] = useState(false) | |
| useEffect(() => { | |
| if (!targetRef.current) return | |
| const observer = new IntersectionObserver((entries) => { | |
| setIsInWindow(entries.some((entry) => entry.isIntersecting)) | |
| }) | |
| observer.observe(targetRef.current) | |
| return () => observer.disconnect() | |
| }, [targetRef]) | |
| return isInWindow | |
| } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment