Skip to content

Instantly share code, notes, and snippets.

@wesokuhara
Last active February 6, 2018 04:03
Show Gist options
  • Save wesokuhara/b94c9403b84dc072156ee1b95a0904b9 to your computer and use it in GitHub Desktop.
Save wesokuhara/b94c9403b84dc072156ee1b95a0904b9 to your computer and use it in GitHub Desktop.
// Often you will need to scroll to the top of a long page, that when navigated to stays scrolled down. Make sure to wrap it in withRouter to give it access to the Router's props.
import React, { Component } from 'react';
import { withRouter } from 'react-router-dom';
class ScrollTopOnNavigation extends Component {
componentDidUpdate(prevProps) {
if (this.props.location !== prevProps.location) {
window.scrollTo(0, 0);
}
}
render() {
return this.props.children;
}
}
export default withRouter(ScrollTopOnNavigation);
// Then render it at the top of your app, but below the Router:
const App = () => (
<BrowserRouter>
<ScrollTopOnNavigation>
{/* ... */}
</ScrollTopOnNavigation>
</BrowserRouter>
);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment