We read every piece of feedback, and take your input very seriously.
To see all available qualifiers, see our documentation.
There was an error while loading. Please reload this page.
1 parent a4f8903 commit 2aa3c90Copy full SHA for 2aa3c90
src/hooks/useHashFragment.js
@@ -0,0 +1,29 @@
1
+import { useEffect } from "react";
2
+
3
+export function useHashFragment(offset = 0, trigger = true) {
4
+ useEffect(() => {
5
+ const scrollToHashElement = () => {
6
+ const { hash } = window.location;
7
+ const elementTOScroll = document.getElementById(hash?.replace("#", ""));
8
9
+ if(!elementTOScroll) {
10
+ return;
11
+ };
12
13
+ window.scrollTo({
14
+ top: elementTOScroll.offsetTop - offset,
15
+ behavior: "smooth"
16
+ });
17
18
19
+ if (!trigger) {
20
21
22
23
+ scrollToHashElement();
24
25
+ window.addEventListener("hashchange", scrollToHashElement);
26
27
+ return () => window.removeEventListener("hashchange", scrollToHashElement);
28
+ }, [trigger]);
29
+}
0 commit comments