manifold/web/components/visibility-observer.tsx
James Grugett c9d323c83f
Small updates to experimental/home (#874)
* Factor out section header

* Remove daily balance change

* Remove dead code

* Layout, add streak

* Fix visibility observer to work on server

* Tweak

* Formatting
2022-09-13 17:47:29 -05:00

24 lines
704 B
TypeScript

import { useEffect, useState } from 'react'
import { useEvent } from '../hooks/use-event'
export function VisibilityObserver(props: {
className?: string
onVisibilityUpdated: (visible: boolean) => void
}) {
const { className } = props
const [elem, setElem] = useState<HTMLElement | null>(null)
const onVisibilityUpdated = useEvent(props.onVisibilityUpdated)
useEffect(() => {
if (elem) {
const observer = new IntersectionObserver(([entry]) => {
onVisibilityUpdated(entry.isIntersecting)
}, {})
observer.observe(elem)
return () => observer.unobserve(elem)
}
}, [elem, onVisibilityUpdated])
return <div ref={setElem} className={className}></div>
}