VisibleObserver.tsx 834 B

123456789101112131415161718192021222324252627282930313233343536
  1. import { useEffect, useRef, useState } from "react";
  2. const useOnScreen = (ref: any) => {
  3. const [isIntersecting, setIntersecting] = useState(false);
  4. const observer = new IntersectionObserver(([entry]) =>
  5. setIntersecting(entry.isIntersecting)
  6. );
  7. useEffect(() => {
  8. observer.observe(ref.current);
  9. return () => {
  10. observer.disconnect();
  11. };
  12. }, []);
  13. return isIntersecting;
  14. };
  15. interface IWidget {
  16. onVisible?: Function;
  17. }
  18. const VisibleObserverWidget = ({ onVisible }: IWidget) => {
  19. const ref = useRef<HTMLDivElement>(null);
  20. const isVisible = useOnScreen(ref);
  21. useEffect(() => {
  22. if (typeof onVisible !== "undefined") {
  23. onVisible(isVisible);
  24. }
  25. }, [isVisible]);
  26. return (
  27. <div ref={ref} style={{ height: 20 }}>
  28. {" "}
  29. </div>
  30. );
  31. };
  32. export default VisibleObserverWidget;