Skip to content

Commit 2aa3c90

Browse files
committed
added hooks
1 parent a4f8903 commit 2aa3c90

File tree

1 file changed

+29
-0
lines changed

1 file changed

+29
-0
lines changed

src/hooks/useHashFragment.js

Lines changed: 29 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -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+
return;
21+
};
22+
23+
scrollToHashElement();
24+
25+
window.addEventListener("hashchange", scrollToHashElement);
26+
27+
return () => window.removeEventListener("hashchange", scrollToHashElement);
28+
}, [trigger]);
29+
}

0 commit comments

Comments
 (0)