IntersectionObserverEntry has wrong boundingClientRect value

22 views Asked by At

My project is developed with React. I made an hook that make an instance of IntersectionObserver and observe a single DOM element. I'm fighting with an issue related to my implementation, seems that the boundingClientRect property has a wrong top constraint, but if i run node.getBoundingClientRect() inside IntersectionObserver callback i'll have the correct top value. Seems, but i'm not sure, that an update of CSS variables (in another component) not update the IntersectionObserver values.

This is my hook

export const useIntersect = (props: Props = {}) => {
  const { rootMargin, root = null, threshold = 0 } = props;
  const [entry, updateEntry] = useState<IntersectionObserverEntry>();
  const [node, setNode] = useState<Element | null>(null);

  const observer = useRef<IntersectionObserver | null>(null);

  useEffect(() => {
    observer.current = new window.IntersectionObserver(
      ([entry]) => {
        updateEntry(entry);
        console.debug(entry);
        console.debug(entry.target.getBoundingClientRect());
      },
      {
        root,
        rootMargin,
        threshold,
      },
    );
    return () => observer.current?.disconnect();
  }, [root, rootMargin, threshold]);

  useEffect(() => {
    if (Utils.isDefined(node)) {
      observer.current?.observe(node);
    }
    return () => {
      if (Utils.isDefined(node)) {
        observer.current?.unobserve(node);
      }
    };
  }, [node]);

  return [setNode, entry] as const;
};

boundingClientRect from IntersectionObserver callback

{
    "x": 80,
    "y": 838.5,
    "width": 384,
    "height": 42,
    "top": 838.5,
    "right": 464,
    "bottom": 880.5,
    "left": 80
}

boundingClientRect from entry.target.getBoundingClientRect() inside callback in which the top is ok

{
    "x": 80,
    "y": 756.5,
    "width": 384,
    "height": 42,
    "top": 756.5,
    "right": 464,
    "bottom": 798.5,
    "left": 80
}
0

There are 0 answers