Skip to content

Instantly share code, notes, and snippets.

@davidfurlong
Last active June 1, 2018 10:33
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save davidfurlong/82f11dfb9ca36de82c5c94583eb59666 to your computer and use it in GitHub Desktop.
Save davidfurlong/82f11dfb9ca36de82c5c94583eb59666 to your computer and use it in GitHub Desktop.
React router 4 scroll to top behaviour, with support for tabs and/or case by case scrolling
// client.js
...
<ScrollToTop>
<App />
</ScrollToTop>
...
// Example usage:
history.push('/about'); // Reset the scroll
history.push('/tab/1', { resetScroll: false }); // Don't reset the scroll
// ScrollToTop.js
import React from 'react';
import { withRouter } from 'react-router-dom';
class ScrollToTop extends React.Component {
componentDidUpdate(prevProps) {
if (prevProps.location && this.props.location !== prevProps.location &&
!(this.props.location.state && this.props.location.state.resetScroll === false)) {
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