Skip to content
Source
Sign inSign up
TanStack/router
Open History to see the last commit

utils.ts

58 lines1.5 KB

1import * as Solid from 'solid-js'
2​
3/**
4 * React hook to wrap `IntersectionObserver`.
5 *
6 * This hook will create an `IntersectionObserver` and observe the ref passed to it.
7 *
8 * When the intersection changes, the callback will be called with the `IntersectionObserverEntry`.
9 *
10 * @param ref - The ref to observe
11 * @param callback - The callback to call when the intersection changes
12 * @param disabled - Whether observation is disabled
13 * @returns The IntersectionObserver instance
14 * @example
15 * ```tsx
16 * const MyComponent = () => {
17 * const ref = React.useRef<HTMLDivElement>(null)
18 * useIntersectionObserver(
19 * ref,
20 * (entry) => { doSomething(entry) },
21 * false
22 * )
23 * return <div ref={ref} />
24 * ```
25 */
26export function useIntersectionObserver<T extends Element>(
27 ref: Solid.Accessor<T | null>,
28 callback: (entry?: IntersectionObserverEntry) => void,
29 disabled: Solid.Accessor<boolean>,
30): Solid.Accessor<IntersectionObserver | null> {
31 const isIntersectionObserverAvailable =
32 typeof IntersectionObserver === 'function'
33 let observerRef: IntersectionObserver | null = null
34​
35 Solid.createEffect(() => {
36 const r = ref()
37 if (disabled() || !r || !isIntersectionObserverAvailable) {
38 Solid.onCleanup(() => callback())
39 return
40 }
41​
42 observerRef = new IntersectionObserver(
43 (entries) => {
44 callback(entries.pop())
45 },
46 { rootMargin: '100px' },
47 )
48​
49 observerRef.observe(r)
50​
51 Solid.onCleanup(() => {
52 observerRef?.disconnect()
53 callback()
54 })
55 })
56​
57 return () => observerRef