Scroll To Top when Route Changes - ReactJS & React Router

kunalukey

Kunal Ukey

Posted on January 2, 2023

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! ❤

💖 💪 🙅 🚩
kunalukey
Kunal Ukey

Posted on January 2, 2023

Join Our Newsletter. No Spam, Only the good stuff.

Sign up to receive the latest update from our blog.

Related