Scroll To Top when Route Changes - ReactJS & React Router
Tags: react, beginners, tutorial, webdev
Published: 2023-01-02 08:37:14

## 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:
```bash
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:
```javascript
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:
```javascript
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
```javascript
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:
```javascript
import { BrowserRouter } from 'react-router-dom';
```

Then, wrap your root component with the `BrowserRouter` component like this:
### index.js
```javascript

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
```javascript
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. 
{% youtube de2_VMxMrQA %}
Happy coding! ❤