How to scroll to the top when changing pages with React Router
January 28, 2019
This is a dead-simple way to make React Router scroll to the top of the page when the page changes:
-
Create a
ScrollToTop
component that scrolls to the top of the window on update. Wrap its export inwithRouter
.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)
-
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!