Scroll to top on page change 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!

I'm Mark Thomas Miller, an engineer, designer, and maker of things.