How to scroll to the top when changing pages with React Router

This is a dead-simple way to make React Router scroll to the top of the page when the page changes:

  1. Create a ScrollToTop component that scrolls to the top of the window on update. Wrap its export in withRouter.

    import React, { Component } from "react";
    import { withRouter } from "react-router-dom";

    class ScrollToTop extends Component {
    componentDidUpdate(prevProps) {
    if (this.props.location !== prevProps.location) {
    window.scrollTo(0, 0);
    }
    }

    render() {
    return <React.Fragment />
    }
    }

    export default withRouter(ScrollToTop)
  2. Add this component to a high-level layout under your Router component.

    const MainLayout = () => (
    <Router>
    <ScrollToTop />
    <OtherAppContents />
    </Router>
    );

Now when you change routes, React Router will update ScrollToTop. This makes the browser scroll to the top of the window, simulating a real page change. Hope this helped!

About the author

I'm Mark Thomas Miller, a full stack engineer and designer currently working at ConvertKit. (We're hiring!) People like Arnold Schwarzenegger, Lindsey Stirling, and Tim Ferriss use features I've built to connect with their fans. I'm currently geeking out about Svelte, mechanical keyboards, and minimalist UI design, and replaying Ocarina of Time.