Skip to content

Instantly share code, notes, and snippets.

@lnmunhoz
Created February 22, 2023 20:51
Show Gist options
  • Save lnmunhoz/701c425194ea85f1145b2b1ec4a0732e to your computer and use it in GitHub Desktop.
Save lnmunhoz/701c425194ea85f1145b2b1ec4a0732e to your computer and use it in GitHub Desktop.
useElementOnScreen hook
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