Initial commit
This commit is contained in:
33
src/components/ScrollToTop.jsx
Normal file
33
src/components/ScrollToTop.jsx
Normal file
@@ -0,0 +1,33 @@
|
||||
import { useEffect } from "react";
|
||||
import { useLocation, useNavigationType } from "react-router-dom";
|
||||
|
||||
const getHashId = (hash) => {
|
||||
const rawId = hash.slice(1);
|
||||
|
||||
try {
|
||||
return decodeURIComponent(rawId);
|
||||
} catch {
|
||||
return rawId;
|
||||
}
|
||||
};
|
||||
|
||||
export default function ScrollToTop() {
|
||||
const { pathname, hash } = useLocation();
|
||||
const navigationType = useNavigationType();
|
||||
|
||||
useEffect(() => {
|
||||
if (navigationType === "POP") return;
|
||||
|
||||
if (hash) {
|
||||
const id = getHashId(hash);
|
||||
const timer = window.setTimeout(() => {
|
||||
document.getElementById(id)?.scrollIntoView({ behavior: "smooth" });
|
||||
}, 50);
|
||||
return () => window.clearTimeout(timer);
|
||||
}
|
||||
|
||||
window.scrollTo({ top: 0, left: 0, behavior: "instant" });
|
||||
}, [pathname, hash, navigationType]);
|
||||
|
||||
return null;
|
||||
}
|
||||
Reference in New Issue
Block a user