Introduction:
Are you looking to implement a feature in your React app that automatically scrolls the user back to the top of the page whenever the route changes? If so, you're in the right place!
In this tutorial, we'll walk through the steps of how to add this functionality to your app. Here's a quick overview of what we'll cover:
- Importing the
useEffecthook and theuseLocationhook from thereact-router-domandreactlibrary. - Creating a custom component that utilizes the
useEffectanduseLocationhooks to scroll to the top of the page whenever the route changes. - Wrapping your app's root component with the
BrowserRoutercomponent from thereact-router-domlibrary. - Adding the custom component to the root component of your app.
Let's get started!
Installation
First, make sure that you have the react-router-dom library installed in your project. You can do this by running the following command in your terminal:
npm install react-router-dom
Custom ScrollToTop Component
Next, inside the src folder create a folder named components and inside that create a file named ScrollToTop.js. Now, open up the file and import the useEffect hook and the useLocation hook from the react-router-dom library like so:
import { useEffect } from 'react';
import { useLocation } from 'react-router-dom';
With these hooks imported, we can now create our custom component that will handle the scrolling behavior.
In the same file, define a new function called ScrollToTop like this:
const ScrollToTop = () => {
// Extracts pathname property(key) from an object
const { pathname } = useLocation();
// Automatically scrolls to top whenever pathname changes
useEffect(() => {
window.scrollTo(0, 0);
}, [pathname]);
}
export default ScrollToTop;
This component uses the useEffect hook to add an effect that is run whenever the route changes. The effect simply scrolls the window to the top of the page using the scrollTo method.
So, the complete code inside will look like this:
ScrollToTop.js
import { useEffect } from 'react';
import { useLocation } from 'react-router-dom';
const ScrollToTop = () => {
// Extracts pathname property(key) from an object
const { pathname } = useLocation();
// Automatically scrolls to top whenever pathname changes
useEffect(() => {
window.scrollTo(0, 0);
}, [pathname]);
}
export default ScrollToTop;
Wrapping Root Component with BrowserRouter
Now that we have our custom component defined, we need to make sure that our app is wrapped in the BrowserRouter component from the react-router-dom library. This component provides the useLocation hook with the information it needs to know when the route has changed.
Import the BrowserRouter component like this:
import { BrowserRouter } from 'react-router-dom';
Then, wrap your root component with the BrowserRouter component like this:
index.js
import React from "react";
import ReactDOM from "react-dom/client";
import "./index.css";
import App from "./App";
import { BrowserRouter } from "react-router-dom";
const root = ReactDOM.createRoot(document.getElementById("root"));
root.render(
<React.StrictMode>
{/* Wrapping App component inside BrowserRouter component */}
<BrowserRouter>
<App />
</BrowserRouter>
</React.StrictMode>
);
Finally, add the ScrollToTop component to your root component like this:
App.js
import ScrollToTop from "./components/ScrollToTop";
function App() {
return (
<div className="App">
{/* ScrollToTop component inside App component */}
<ScrollToTop />
</div>
);
}
export default App;
And that's it! With these changes in place, your app should now automatically scroll to the top of the page whenever the route changes.
I hope this tutorial was helpful in showing you how to implement this feature in your React app. If you have any questions or run into any issues, don't hesitate to ask for help.
Happy coding! ❤
Top comments (6)
I can't get it to work reliably on iOS Safari. It works fine on all other browsers and on Android. I have found people complaining about this on forums but I don't really understand their solutions, if they even are solutions. Is this problem known to you?
Thanks for a super clear explanation!
Saved me today. thanks!
@react-refresh:278 Uncaught Error: ScrollToTop(...): Nothing was returned from render. This usually means a return statement is missing. Or, to render nothing, return null.
Is there way to stop scroll to top if someone click back button[ If someone press back it restore the last posotion]
@akashthakur05 you can store the previous pathname to state whenever the path changes and only scroll to top when the current pathname does not match the previous pathname.
What if I am using the height as 100 vh