-
-
Notifications
You must be signed in to change notification settings - Fork 93
Expand file tree
/
Copy pathScrollToHashId.tsx
More file actions
46 lines (37 loc) · 1.17 KB
/
ScrollToHashId.tsx
File metadata and controls
46 lines (37 loc) · 1.17 KB
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 } from "react";
import { useLocation } from "@docusaurus/router";
/**
* Scrolls to the element with the ID matching the current hash in the URL.
* This is needed when a hash ID is provided in the initial load to scroll to a heading rendered by a react component.
*/
export function ScrollToHashId() {
const location = useLocation();
useEffect(() => {
if (location.hash) {
const id = location.hash.replace("#", "");
const delay = 100;
let attemptsLeft = 5;
const scrollToId = () => {
const element = document.getElementById(id);
if (element != null) {
if (isElementAtTop(element)) {
return;
}
element.scrollIntoView();
}
attemptsLeft--;
if (attemptsLeft > 0) {
setTimeout(scrollToId, delay);
}
};
setTimeout(scrollToId, delay);
}
// oxlint-disable-next-line eslint-plugin-react-hooks/exhaustive-deps
}, []);
return null;
}
function isElementAtTop(el: HTMLElement, tolerance = 10) {
const rect = el.getBoundingClientRect();
// 68px is the offset for the navbar
return Math.abs(rect.top - 68) <= tolerance;
}