Created
February 22, 2023 20:51
-
-
Save lnmunhoz/701c425194ea85f1145b2b1ec4a0732e to your computer and use it in GitHub Desktop.
useElementOnScreen hook
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, useRef, useState } from 'react'; | |
import * as React from 'react'; | |
export type UseElementOnScreenProps = [React.MutableRefObject<any>, boolean]; | |
export const useElementOnScreen = (options?: IntersectionObserverInit): UseElementOnScreenProps => { | |
const containerRef = useRef(null); | |
const [isVisible, setIsVisible] = useState(false); | |
const callbackFunction = (entries) => { | |
const [entry] = entries; | |
setIsVisible(entry.isIntersecting); | |
}; | |
useEffect(() => { | |
const observer = new IntersectionObserver(callbackFunction, options); | |
if (containerRef.current) observer.observe(containerRef.current); | |
return () => { | |
// eslint-disable-next-line react-hooks/exhaustive-deps | |
if (containerRef.current) observer.unobserve(containerRef.current); | |
}; | |
}, [containerRef, options]); | |
return [containerRef, isVisible]; | |
}; | |
export type WithElementOnScreenProps = { | |
elementOnScreenRef: React.MutableRefObject<any>; | |
isElementOnScreen: boolean; | |
}; | |
export function withElementOnScreen(WrappedComponent, options?: IntersectionObserverInit) { | |
return (props) => { | |
const [containerRef, isVisible] = useElementOnScreen(options); | |
return ( | |
<WrappedComponent | |
elementOnScreenRef={containerRef} | |
isElementOnScreen={isVisible} | |
{...props} | |
/> | |
); | |
}; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment