Skip to content

Instantly share code, notes, and snippets.

@p32929
Created May 23, 2024 10:29
Show Gist options
  • Save p32929/10056b3a23805e75bcaf17b65fc149ba to your computer and use it in GitHub Desktop.
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
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;
@p32929
Copy link
Author

p32929 commented May 23, 2024

how to use:

<VisibilityObserver>
  {({ elementRef, isVisible }) => (
    <div className="flex lg:hidden flex-col h-full" ref={elementRef}>
      Hello world
    </div>
  )}
</VisibilityObserver>;

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment