portfolio/src/components/ScrollToAnchor.jsx
Mariia Shabelnik 03711da9ef
All checks were successful
ci/cd / Build (push) Successful in 18s
added update
2024-01-02 23:04:17 +01:00

29 lines
856 B
JavaScript

import { useEffect, useRef } from "react";
import { useLocation } from "react-router-dom";
function ScrollToAnchor() {
const location = useLocation();
const lastHash = useRef("");
// listen to location change using useEffect with location as dependency
// https://jasonwatmore.com/react-router-v6-listen-to-location-route-change-without-history-listen
useEffect(() => {
if (location.hash) {
lastHash.current = location.hash.slice(1); // safe hash for further use after navigation
}
if (lastHash.current && document.getElementById(lastHash.current)) {
setTimeout(() => {
document
.getElementById(lastHash.current)
?.scrollIntoView({ behavior: "smooth", block: "start" });
lastHash.current = "";
}, 100);
}
}, [location]);
return null;
}
export default ScrollToAnchor;