How to make React Router scroll to top on page change

January 28, 2019
I'm making an alternative to DevTools. Click here to check it out.

If you want to make React Router scroll to the top of the page when the route changes, you can create a simple ScrollToTop component like so:

// ScrollToTop.jsx

import React from 'react'
import { withRouter } from 'react-router-dom'

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

	render() {
		return this.props.children
	}
}

Add it to a high-level layout so you don’t need to repeat it on every page:

const MainLayout = () => (
	<div>
		...
		<ScrollToTop />
		...
	</div>
)

Now when you change routes, React Router will update ScrollToTop, making the window scroll to the top of the page. This behavior is more ideal for most sites.