/* Add your custom styles here */
Scroll To Top on Route Change In ReactJS | Scroll To Top On Page Change (React Router)
Implementing a scroll-to-top functionality on route change in a ReactJS application using React Router can improve the user experience and ensure that users are always presented with the content at the top of the page when navigating between different routes.
One way to achieve this is by utilizing the React Router’s scrollRestoration
feature, which enables the preservation of the scroll position on route changes. By setting scrollRestoration
to auto
or manual
, the browser will attempt to restore the scroll position on history navigation. However, this approach may not work consistently across all browsers and might not provide the desired behavior.
Alternatively, we can use React’s useEffect
hook to detect route changes and scroll to the top of the page. Here’s an example of how this can be done:
import React, { useEffect } from 'react';
import { useLocation } from 'react-router-dom';
const ScrollToTop = () => {
const location = useLocation();
useEffect(() => {
window.scrollTo(0, 0);
}, [location.pathname]);
return null;
};
export default ScrollToTop;
In this example, we create a component called ScrollToTop
that utilizes the useEffect
hook to trigger a scroll to the top of the page whenever the location.pathname
changes. By including this component in the root of our application and rendering it inside the Router
component, we can ensure that the page is scrolled to the top on every route change.
To implement the scroll-to-top functionality in your ReactJS application, simply add the ScrollToTop
component to your routes and enjoy a seamless scrolling experience for your users.
⭐⭐⭐ Video Sponsored by: Famoid ⭐⭐⭐
• Get Instagram Followers: https://famoid.com/buy-instagram-followers
• Get TikTok Followers: https://famoid.com/buy-tiktok-followers
• Get Facebook Page Likes: https://famoid.com/buy-facebook-fanpage-likes
• Get YouTube Subscribers: https://famoid.com/buy-real-youtube-subscribers
simple and short, thanks
Thank u man!
Thanks
I actually did everything same just I keep getting error that I can't use useLocation if its not in context of Route component…
Thank you 👍
Thanks man
Thank you so much
It helps a lots
Thank you so much
You saved me and my time Thanks to You my friend <3
How to "inject" it into my react router, when I'm using createBrowserRouter() and then <RouterProvider /> ?
Thank You 😊