Skip to content

Instantly share code, notes, and snippets.

@searleb
Created December 15, 2017 03:26
Show Gist options
  • Save searleb/8e47a5e769502489747e7dc12b5316dc to your computer and use it in GitHub Desktop.
Save searleb/8e47a5e769502489747e7dc12b5316dc to your computer and use it in GitHub Desktop.
Scroll to top on URL change
// Wrap routes <Switch>
import { Component } from 'react'
import { withRouter } from 'react-router-dom'
import PropTypes from 'prop-types'
class ScrollToTop extends Component {
static propTypes = {
location: PropTypes.object.isRequired,
children: PropTypes.element.isRequired,
}
componentDidUpdate(prevProps) {
if (this.props.location !== prevProps.location) {
window.scrollTo(0, 0)
}
}
render() {
return this.props.children
}
}
export default withRouter(ScrollToTop)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment