/
index.js
52 lines (42 loc) · 1.16 KB
/
index.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
import { useState, useEffect } from "react";
const INTERSECTION_OBSERVER_CONFIG = {
threshold: 0.0,
triggerOnce: true,
rootMargin: "0px"
};
/**
* React hook that return is the object is intersected
*/
function useIntersectionObserver(ref, config = {}, rootRef = null) {
const [isIntersecting, setIntersecting] = useState(false);
const options = {
root: rootRef && rootRef.current,
...INTERSECTION_OBSERVER_CONFIG,
...config
};
useEffect(() => {
const observer = new IntersectionObserver(function(entries) {
if (options.triggerOnce) {
if (entries[0].isIntersecting) {
setIntersecting(true);
observer.unobserve(ref.current);
}
} else {
setIntersecting(entries[0].isIntersecting);
}
}, options);
if (!ref) {
console.warn(
`No target specified - use useRef() hook to pass the target value`
);
return;
}
const { current } = ref;
observer.observe(current);
return () => {
if (current) observer.unobserve(current);
};
}, [options, ref, options.triggerOnce]);
return isIntersecting;
}
export default useIntersectionObserver;