-
Notifications
You must be signed in to change notification settings - Fork 5.1k
/
Copy pathuseActiveHash.ts
46 lines (41 loc) · 1.15 KB
/
useActiveHash.ts
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
import { useEffect, useState } from "react"
/**
* A hook to determine which section of the page is currently in the viewport.
* @param {*} itemIds Array of document ids to observe
* @param {*} rootMargin
* @returns id of the element currently in viewport
*/
export const useActiveHash = (
itemIds: Array<string>,
rootMargin = `0% 0% -80% 0%`
): string => {
const [activeHash, setActiveHash] = useState(``)
useEffect(() => {
const observer = new IntersectionObserver(
(entries) => {
entries.forEach((entry) => {
if (entry.isIntersecting) {
setActiveHash(`#${entry.target.id}`)
}
})
},
{ rootMargin }
)
itemIds?.forEach((id) => {
// Remove # from id. EX: #element-id -> element-id
const element = document.getElementById(id.replace("#", ""))
if (element !== null) {
observer.observe(element)
}
})
return () => {
itemIds?.forEach((id) => {
const element = document.getElementById(id)
if (element !== null) {
observer.unobserve(element)
}
})
}
}, [itemIds, rootMargin])
return activeHash
}