'creating custom hook with IntersectionObserver API in React
I'm using some boilerplate code for utilizing the intersectionObserver in React. Which works well and how I would expect.
const containerRef = useRef(null)
const [isVisible, setIsVisible] = useState(false)
console.log('is visible =>', isVisible)
const callbackFunction = (entries) => {
const [entry] = entries
setIsVisible(entry.isIntersecting)
}
const options = {
root: null,
rootMargin: '0px',
threshold: 1.0
}
useEffect(() => {
const observer = new IntersectionObserver(callbackFunction, options)
if (containerRef.current) observer.observe(containerRef.current)
return () => {
if (containerRef.current) observer.unobserve(containerRef.current)
}
}, [containerRef, options])
The useEffect is currently only watching the specific useRef that I have told it to but what if I want to apply this same functionality to multiple elements on the page without copying code and without a bunch of if else statements. Is there any way to utilize this more dynamically?
<div style={{ height: '100vh', backgroundColor: 'black', color: 'white' }}>
<h1 ref={containerRef} style={{ fontSize: '5rem' }}>NEW CONTENT</h1>
<p ref={// another ref to watch} style={{ fontSize: '5rem', marginTop: '10rem' }}>NEW CONTENT TWO</p>
</div>
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|
