Created
May 23, 2024 10:29
-
-
Save p32929/10056b3a23805e75bcaf17b65fc149ba to your computer and use it in GitHub Desktop.
a component kinda thingie to detect if an element is visible or hidden by css and came to view etc
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 React, { useState, useEffect, useRef } from 'react'; | |
interface VisibilityObserverProps { | |
children: (props: { elementRef: React.RefObject<HTMLDivElement>, isVisible: boolean }) => JSX.Element; | |
} | |
const VisibilityObserver: React.FC<VisibilityObserverProps> = ({ children }) => { | |
const [isVisible, setIsVisible] = useState(false); | |
const elementRef = useRef<HTMLDivElement>(null); | |
useEffect(() => { | |
const observer = new IntersectionObserver( | |
([entry]) => { | |
setIsVisible(entry.isIntersecting); | |
// console.log(`VisibilityObserver :: useEffect :: entry.isIntersecting -> `, entry.isIntersecting); | |
}, | |
{ threshold: [0] } | |
); | |
if (elementRef.current) { | |
observer.observe(elementRef.current); | |
} | |
return () => { | |
if (elementRef.current) { | |
observer.unobserve(elementRef.current); | |
} | |
}; | |
}, []); | |
return children({ elementRef, isVisible }); | |
}; | |
export default VisibilityObserver; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
how to use: