DEV Community

Cover image for Scroll to top on page change React
Stephen Akugbe
Stephen Akugbe

Posted on

4

Scroll to top on page change React

If you are using React Router Dom for navigation and routing in your React app then you will notice that if you have a long content page and then you navigate to another long content page, you will stay scrolled down. This doesn't tell of a good user experience and as such you'll want the new page to be displayed from the top.
This short piece would show you how to complete that would having to add the same piece of code to every component or pages rendered in your react app. To accomplish this, we will make use of the useEffect hook and the useLocation hooks to achieve this.

NB: This article assumes you are already familiar with React-Router and you have already installed it in your react application.

First, you'll create a new wrapper component that handles the scroll restoration when you open a new page. For my

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

const ScrollToTop = (props) => {
    const location = useLocation();
    useEffect(() => {
      window.scrollTo({top: 0, left: 0, behavior: 'smooth' });
    }, [location]);

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

export default ScrollToTop;
Enter fullscreen mode Exit fullscreen mode

Next, import this wrapper component in your App.js and add it as a wrapper component within your Router as shown below.

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

const App = () => {
  return (
    <Router>
      <ScrollToTop>
        <Routes>
          {* All your other imported components *}
        </Routes>
      </ScrollToTop>
    </Router>
  );
};

export default App;
Enter fullscreen mode Exit fullscreen mode

Notice that the ScrollToTop component wraps the Routes component but stays inside the Router component. This order is important and must be followed to achieve the desired result.

Thanks for reading and don't forget to drop a like if this article helped you.

Sentry blog image

How to reduce TTFB

In the past few years in the web dev world, we’ve seen a significant push towards rendering our websites on the server. Doing so is better for SEO and performs better on low-powered devices, but one thing we had to sacrifice is TTFB.

In this article, we’ll see how we can identify what makes our TTFB high so we can fix it.

Read more

Top comments (0)

The best way to debug slow web pages cover image

The best way to debug slow web pages

Tools like Page Speed Insights and Google Lighthouse are great for providing advice for front end performance issues. But what these tools can’t do, is evaluate performance across your entire stack of distributed services and applications.

Watch video