Fixing React Router Scroll Navigation.


React router is one of the most used routing solutions for React applications. Though there are other solutions, this is my default choice for routing unless I am using Next.js. I have worked on different projects with React Router and have noticed an issue with scroll behavior. When I click on the <Link>
tag and navigate to another page, it does not start from the top of the page. This can be annoying, but there is a fix. I will be sharing the solution I found that has helped me resolve this issue.
Create a component and name it
ScrollToTop
(any name would work as long as it clearly defines the purpose).
import { useEffect } from 'react';
import { useLocation } from 'react-router-dom';
function ScrollToTop() { const { pathname } = useLocation();
useEffect(() => { window.scrollTo(0, 0); }, [pathname]);
return null; }
Place the component into your main route component.
function App() { return ( <ScrollToTop/> {/* Your routes */} ); }
With this, the issue is fixed. In case you do not know what the useLocation
hook does, you can read more about it in the React Router official docs.
I hope you found this helpful! If you have a better solution, feel free to share it in the comments. Thank you!
Subscribe to my newsletter
Read articles from Idorenyin Akaninyene directly inside your inbox. Subscribe to the newsletter, and don't miss out.
Written by
