1 | import { RefObject, useEffect } from 'react' |
||
2 | |||
3 | interface IProps { |
||
4 | root?: Element | Document | null | undefined |
||
5 | target: RefObject<HTMLElement> |
||
6 | onIntersect: () => void |
||
7 | threshold?: number |
||
8 | rootMargin?: string |
||
9 | enabled: boolean |
||
10 | } |
||
11 | |||
12 | export const useIntersectionObserver = ({ |
||
13 | root = null, |
||
14 | target, |
||
15 | onIntersect, |
||
16 | threshold = 1.0, |
||
17 | rootMargin = '900px', |
||
18 | enabled = false, |
||
19 | }: IProps) => { |
||
20 | useEffect(() => { |
||
21 | if (!enabled) { |
||
22 | return |
||
23 | } |
||
24 | |||
25 | const observer = new IntersectionObserver( |
||
26 | entries => |
||
27 | entries.forEach(entry => entry.isIntersecting && onIntersect()), |
||
28 | { |
||
29 | root, |
||
30 | rootMargin, |
||
31 | threshold, |
||
32 | }, |
||
33 | ) |
||
34 | const el = target?.current |
||
35 | |||
36 | if (!el) { |
||
37 | return |
||
38 | } |
||
39 | |||
40 | observer.observe(el) |
||
41 | |||
42 | return () => { |
||
43 | observer.unobserve(el) |
||
44 | } |
||
45 | }, [target.current, enabled]) |
||
0 ignored issues
–
show
introduced
by
![]() |
|||
46 | } |
||
47 |