forked from untitleduico/react
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathuse-active-item.ts
More file actions
36 lines (31 loc) · 989 Bytes
/
use-active-item.ts
File metadata and controls
36 lines (31 loc) · 989 Bytes
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
import { useEffect, useState } from "react";
export function useActiveItem(itemIds: string[]) {
const [activeId, setActiveId] = useState("");
useEffect(() => {
const observer = new IntersectionObserver(
(entries) => {
entries.forEach((entry) => {
if (entry.isIntersecting) {
setActiveId(entry.target.id);
}
});
},
{ rootMargin: `0% 0% -80% 0%` },
);
itemIds?.forEach((id) => {
const element = document.getElementById(id);
if (element) {
observer.observe(element);
}
});
return () => {
itemIds?.forEach((id) => {
const element = document.getElementById(id);
if (element) {
observer.unobserve(element);
}
});
};
}, [itemIds]);
return activeId;
}