With React Router navigation if your links are located somewhere not in the top of the page once you go to a new page your scroll position would be where it was, sometimes in the bottom of the page. There is an easy fix to that.
The idea is to create a useEffect
watching any changes in the URL and once triggered it will scroll the current view to top. Pretty simple.
We can create a component ScrollToTop.js
:
import { useEffect } from "react";
import { useLocation } from "react-router";
export default function ScrollToTop() {
const { pathname } = useLocation();
useEffect(() => {
document.documentElement.scrollTo({
top: 0,
left: 0,
behavior: "instant", // Optional if you want to skip the scrolling animation
});
}, [pathname]);
return null;
}
And then in you main file where you declare routes import it and add inside the Router
before the Routes
, for example:
<Router>
<ScrollToTop />
<Routes>
<Route path="/" element={<Home />} />
{/* rest of your routes */}
</Routes>
</Router>
And that's all. Now even if you click on a link somewhere in the bottom of your page to change the URL the new view will open scrolled to top.
Thanks!
Top comments (0)