2021-10-28 15:02:22 +00:00
|
|
|
import React from "react";
|
|
|
|
|
|
|
|
const isInteractionObserverSupported = typeof window !== "undefined" && "IntersectionObserver" in window;
|
|
|
|
|
|
|
|
export const useInViewObserver = (onInViewCallback: () => void) => {
|
2022-06-06 18:24:37 +00:00
|
|
|
const [node, setRef] = React.useState<HTMLElement | null>(null);
|
2021-10-28 15:02:22 +00:00
|
|
|
|
|
|
|
const onInViewCallbackRef = React.useRef(onInViewCallback);
|
|
|
|
onInViewCallbackRef.current = onInViewCallback;
|
|
|
|
|
|
|
|
React.useEffect(() => {
|
|
|
|
if (!isInteractionObserverSupported) {
|
|
|
|
// Skip interaction check if not supported in browser
|
|
|
|
return;
|
|
|
|
}
|
|
|
|
|
|
|
|
let observer: IntersectionObserver;
|
|
|
|
if (node && node.parentElement) {
|
|
|
|
observer = new IntersectionObserver(
|
|
|
|
([entry]) => {
|
|
|
|
if (entry.isIntersecting) {
|
|
|
|
onInViewCallbackRef.current();
|
|
|
|
}
|
|
|
|
},
|
|
|
|
{
|
|
|
|
root: document.body,
|
|
|
|
}
|
|
|
|
);
|
|
|
|
observer.observe(node);
|
|
|
|
}
|
|
|
|
|
|
|
|
return () => {
|
|
|
|
if (observer) {
|
|
|
|
observer.disconnect();
|
|
|
|
}
|
|
|
|
};
|
|
|
|
}, [node]);
|
|
|
|
|
|
|
|
return {
|
|
|
|
ref: setRef,
|
|
|
|
};
|
|
|
|
};
|