Kinda Code
Home/React/React Router Dom: Scroll To Top on Route Change

React Router Dom: Scroll To Top on Route Change

Last updated: March 03, 2023

If you are using React Router Dom for navigation and routing in your React app then you will have to handle scroll restoration on your own because the library no longer ships default scroll management (it used to provide an out-of-the-box solution in the past).

By default, if you have a long content page and then you navigate to another long content page, you will stay scrolled down. This behavior doesn’t make lots of sense because not many people like to read text upside down. The example below will show you how to automatically scroll to the top of the page on each route change. We will use the useEffect hook and the useLocation hook to get the job done.

Note: This article was recently updated to work properly with React Router 6.x and later. However, the code snippet for React Router 5.x is still available at the end of this tutorial for your reference.

The Example

Preview

Our example project has 2 routes, “/” (LandingPage) and “/product” (ProductPage). Each page is very long and has a Link component so we can navigate to the other page.

The Steps

1. Create a new React project and Install react-router-dom:

npm install react-router-dom --save

2. Create a wrapper component that handles scroll restoration for you:

// src/ScrollToTop.jsx
import { useEffect } from "react";
import { useLocation } from "react-router";

const ScrollToTop = (props) => {
  const location = useLocation();
  useEffect(() => {
    window.scrollTo(0, 0);
  }, [location]);

  return <>{props.children}</>
};

export default ScrollToTop;

3. Create a file named LandingPage.jsx in your src folder and add the following:

// src/LandingPage.jsx
import { Link } from "react-router-dom";

const LandingPage = (props) => {
  return (
    <div style={{ margin: "auto", width: "80%" }}>
      <h1>Landing Page</h1>
      <div style={{ backgroundColor: "pink", height: 700 }}></div>
      <div style={{ backgroundColor: "orange", height: 700 }}></div>
      <div style={{ backgroundColor: "purple", height: 700 }}></div>
      <Link to="/product">
        <h2>Go To Product Page</h2>
      </Link>
    </div>
  );
};

export default LandingPage;

4. Similarly, create a file named ProductPage.jsx in the src folder and add the following code:

// src/ProductPage.jsx
import { Link } from "react-router-dom";

const ProductPage = (props) => {
  return (
    <div style={{ margin: "auto", width: "80%" }}>
      <h1>Product Page</h1>
      <div style={{ backgroundColor: "green", height: 700 }}></div>
      <div style={{ backgroundColor: "grey", height: 700 }}></div>
      <div style={{ backgroundColor: "blueviolet", height: 700 }}></div>
      <Link to="/">
        <h2>Go To Home Page</h2>
      </Link>
    </div>
  );
};

export default ProductPage;

5. Last but not least, remove all the default code in App.js.

If you’re using React Router 6 or newer, add this:

// App.js
// Kindacode.com
import { BrowserRouter as Router, Routes, Route } from "react-router-dom";

import LandingPage from "./LandingPage";
import ProductPage from "./ProductPage";
import ScrollToTop from "./ScrollToTop";

const App = () => {
  return (
    <Router>
      <ScrollToTop>
        <Routes>
          <Route path="/" element={<LandingPage />} />
          <Route path="/product" element={<ProductPage />} />
        </Routes>
      </ScrollToTop>
    </Router>
  );
};

export default App;

Notice that the ScrollToTop component wraps the Routes component but stays inside the Router component. The order is important.

If you’re working with React Router 5.x, use this:

// App.js
// Kindacode.com
import {
  BrowserRouter as Router,
  Route,
  Switch,
} from "react-router-dom";

import LandingPage from "./LandingPage";
import ProductPage from "./ProductPage";
import ScrollToTop from "./ScrollToTop";

const App = () => {
  return (
    <Router>
      <ScrollToTop>
        <Switch>
          <Route path="/" exact>
            <LandingPage />
          </Route>

          <Route path="/product">
            <ProductPage />
          </Route>
        </Switch>
      </ScrollToTop>
    </Router>
  );
};

export default App;

Notice that the ScrollToTop component wraps the Switch component but stays inside the Router component.

Conclusion

We’ve built a simple single-page app to demonstrate how to programmatically scroll to the top of the page on every route change. If you’d like to learn more about modern React and frontend development, take a look at the following articles:

You can also check our React category page and React Native category page for the latest tutorials and examples.

Related Articles