Last active
December 2, 2019 14:32
-
-
Save madflanderz/7a514e4ac17fea3236efdfa42b39b43f to your computer and use it in GitHub Desktop.
Hooks - React Intersection
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" | |
/** | |
Usage: | |
// Ref for the element that we want to detect whether on screen | |
const ref = useRef<HTMLDivElement>(null) | |
// Call the hook passing in ref and root margin | |
// In this case it would only be considered onScreen if more ... | |
// ... than 300px of element is visible. | |
const onScreen = useOnScreen(ref, "300px") | |
*/ | |
// Hook | |
export default function useOnScreen( | |
ref: React.RefObject<HTMLElement>, | |
rootMargin = "0px" | |
) { | |
// State and setter for storing whether element is visible | |
const [isIntersecting, setIntersecting] = useState(false) | |
useEffect(() => { | |
const observer = new IntersectionObserver( | |
([entry]) => { | |
// Update our state when observer callback fires | |
setIntersecting(entry.isIntersecting) | |
}, | |
{ | |
rootMargin, | |
} | |
) | |
const element = ref.current | |
if (element) { | |
observer.observe(element) | |
} | |
return () => { | |
if (element) { | |
observer.unobserve(element) | |
} | |
} | |
}, [ref, rootMargin]) | |
return isIntersecting | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment