Design Converter
Education
Last updated on Mar 17, 2025
•4 mins read
Last updated on Mar 17, 2025
•4 mins read
Software Development Executive - I
He writes code, breaks things, fixes them, and then does it all over again!
Tired of scrolling back up after navigating through a site?
A react scroll to top on route change feature can fix that! It makes the user experience smoother by automatically scrolling to the top when the route changes.
This blog will walk you through how to add this feature in React using React Router. We'll keep it simple and cover some best practices along the way.
Let’s get started!
When users navigate between pages in a React application, especially single-page applications (SPAs), the scroll position often remains unchanged. This behavior can be disorienting, particularly when the new page's content doesn't align with the previous scroll position. Implementing a scroll-to-top feature addresses this issue by resetting the scroll position to the top of the page upon route transitions, providing a consistent and intuitive navigation experience.
Before proceeding, ensure you have the following:
• React: A JavaScript library for building user interfaces.
• React Router: A standard library for routing in React applications.
React Router provides hooks and components that facilitate navigation and routing in React applications. To implement the scroll-to-top functionality, follow these steps:
1import { useEffect } from 'react'; 2import { useLocation } from 'react-router-dom'; 3 4const ScrollToTop = () => { 5 const { pathname } = useLocation(); 6 7 useEffect(() => { 8 window.scrollTo(0, 0); 9 }, [pathname]); 10 11 return null; 12}; 13 14export default ScrollToTop;
In this component:
• useLocation hook from React Router provides access to the current location object, which includes the pathname.
• useEffect hook listens for changes in the pathname. Upon detection, it triggers window.scrollTo(0, 0), resetting the scroll position to the top.
This approach ensures that every time the route changes, the page scrolls to the top, enhancing the user experience.
1import { BrowserRouter as Router, Routes, Route } from 'react-router-dom'; 2import ScrollToTop from './ScrollToTop'; 3import HomePage from './HomePage'; 4import AboutPage from './AboutPage'; 5 6function App() { 7 return ( 8 <Router> 9 <ScrollToTop /> 10 <Routes> 11 <Route path="/" element={<HomePage />} /> 12 <Route path="/about" element={<AboutPage />} /> 13 {/* Add more routes as needed */} 14 </Routes> 15 </Router> 16 ); 17} 18 19export default App;
Here, the ScrollToTop component is placed inside the Router but outside the Routes. This positioning ensures that it can detect route changes and adjust the scroll position appropriately across all defined routes.
To further improve the navigation experience, consider adding smooth scrolling behavior. This effect provides a gradual transition to the top of the page, making the navigation feel more natural.
1html { 2 scroll-behavior: smooth; 3}
This rule applies smooth scrolling to all anchor links and programmatic scrolls within the application.
1useEffect(() => { 2 window.scrollTo({ 3 top: 0, 4 left: 0, 5 behavior: 'smooth', 6 }); 7}, [pathname]);
By setting the behavior property to 'smooth', the scroll action becomes animated, enhancing the user experience.
React Router v6 introduced changes in how scroll restoration is handled. To implement scroll-to-top functionality in v6, you can utilize the useLayoutEffect hook for immediate effect before the paint:
1import { useLayoutEffect } from 'react'; 2import { useLocation } from 'react-router-dom'; 3 4const ScrollToTop = () => { 5 const { pathname } = useLocation(); 6 7 useLayoutEffect(() => { 8 window.scrollTo(0, 0); 9 }, [pathname]); 10 11 return null; 12}; 13 14export default ScrollToTop;
Using useLayoutEffect ensures that the scroll position is reset before the browser repaints, preventing any visual inconsistencies during navigation.
For applications with complex routing or nested routes, you might need to implement scroll restoration that considers the scroll position of individual elements or sections. This requires a more nuanced approach, such as:
• Saving Scroll Position: Before a route change, store the current scroll position of relevant elements.
• Restoring Scroll Position: After the route change and component re-render, programmatically set the scroll position of elements to their saved positions.
This approach can be particularly useful for applications with tabbed interfaces or dynamically loaded content.
Adding a scroll-to-top feature on route changes in React makes navigation smoother and more user-friendly. Using React Router's hooks like useLocation and React’s useEffect or useLayoutEffect helps developers manage scroll behavior easily. By applying these methods, a React app can deliver a more intuitive and polished user experience.
Tired of manually designing screens, coding on weekends, and technical debt? Let DhiWise handle it for you!
You can build an e-commerce store, healthcare app, portfolio, blogging website, social media or admin panel right away. Use our library of 40+ pre-built free templates to create your first application using DhiWise.