-
-
Save lu2000luk/cc1b26bdc5ff33de03ebbfb7f46d2ee3 to your computer and use it in GitHub Desktop.
React custom hook to observe an element is visible in viewport or not
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 { useEffect, useState, useRef } from "react"; | |
export const useIntersection = (element: { current: any }, rootMargin: any) => { | |
const [isVisible, setState] = useState(false); | |
useEffect(() => { | |
const current = element?.current; | |
const observer = new IntersectionObserver( | |
([entry]) => { | |
setState(entry.isIntersecting); | |
}, | |
{ rootMargin } | |
); | |
current && observer?.observe(current); | |
return () => current && observer.unobserve(current); | |
}, []); | |
return isVisible; | |
}; | |
export const onViewElement = ({ callbackFn, children }: { callbackFn: any; children: any }) => { | |
const triggerRef = useRef(null); | |
const isVisible = useIntersection(triggerRef, "0px"); | |
useEffect(() => { | |
if (isVisible) { | |
callbackFn(); | |
} | |
}, [callbackFn, isVisible]); | |
return (<div ref={triggerRef}>{children}</div>); | |
}; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment