DEV Community

Cover image for Scroll To Top when Route Changes - ReactJS & React Router
Kunal Ukey
Kunal Ukey

Posted on

Scroll To Top when Route Changes - ReactJS & React Router

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:

  1. Importing the useEffect hook and the useLocation hook from the react-router-dom and react library.
  2. Creating a custom component that utilizes the useEffect and useLocation hooks to scroll to the top of the page whenever the route changes.
  3. Wrapping your app's root component with the BrowserRouter component from the react-router-dom library.
  4. 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
Enter fullscreen mode Exit fullscreen mode

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';
Enter fullscreen mode Exit fullscreen mode

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;
Enter fullscreen mode Exit fullscreen mode

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;
Enter fullscreen mode Exit fullscreen mode

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';
Enter fullscreen mode Exit fullscreen mode

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> 
); 

Enter fullscreen mode Exit fullscreen mode

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;
Enter fullscreen mode Exit fullscreen mode

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)

Collapse
 
hv123 profile image
Haris Vidimlic

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!

Collapse
 
akashthakur05 profile image
Akash Singh • Edited

Is there way to stop scroll to top if someone click back button[ If someone press back it restore the last posotion]

Collapse
 
kunalukey profile image
Kunal Ukey

@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.

Collapse
 
seojeek profile image
Alex Vallejo

@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.

Collapse
 
topboyasante profile image
Nana K.

Saved me today. thanks!

Collapse
 
devesh_singh_db11132f42be profile image
Devesh Singh

What if I am using the height as 100 vh