Cannot use the intersection Observer Api in the @shopify/hydrogen remix app

120 Views Asked by At

I have used many packages like react-intersection-observer and @shopify/react-intersection-observer but it does not observe the element

I have also created a component that still would not work

import React, {useEffect, useRef, useState} from 'react';

function InView(props) {
  const ref = useRef();
  const observerRef = useRef(null);
  const [isInView, setIsInView] = useState(false);

  const handleIntersection = (entries) => {
    entries.forEach((entry) => {
      if (entry.isIntersecting) {
        setIsInView(true);
        observerRef.current.unobserve(entry.target);
      }
    });
  };

  useEffect(() => {
    if (typeof window !== 'undefined') {
      // Check if running on the client
      observerRef.current = new IntersectionObserver(handleIntersection, {
        threshold: 0.5,
      });

      // Start observing the element when it's available on the client side
      if (ref.current) {
        observerRef.current.observe(ref.current);
      }

      return () => {
        if (observerRef.current) {
          observerRef.current.disconnect();
        }
      };
    }
  }, []);

  return (
    <div ref={(node) => (ref.current = node)}>
      {props.children({
        isInView,
      })}
    </div>
  );
}

export default InView;

It still does not works

0

There are 0 best solutions below