diff --git a/src/components/intersection-view.jsx b/src/components/intersection-view.jsx new file mode 100644 index 00000000..0763e6b9 --- /dev/null +++ b/src/components/intersection-view.jsx @@ -0,0 +1,29 @@ +import { useLayoutEffect, useRef, useState } from 'preact/hooks'; + +const IntersectionView = ({ children, root = null, fallback = null }) => { + const ref = useRef(); + const [show, setShow] = useState(false); + useLayoutEffect(() => { + const observer = new IntersectionObserver( + (entries) => { + const entry = entries[0]; + if (entry.isIntersecting) { + setShow(true); + observer.unobserve(ref.current); + } + }, + { + root, + rootMargin: `${screen.height}px`, + }, + ); + if (ref.current) observer.observe(ref.current); + return () => { + if (ref.current) observer.unobserve(ref.current); + }; + }, []); + + return show ? children :
{fallback}
; +}; + +export default IntersectionView;