Last active
June 1, 2018 10:33
-
-
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
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// client.js | |
... | |
<ScrollToTop> | |
<App /> | |
</ScrollToTop> | |
... |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// Example usage: | |
history.push('/about'); // Reset the scroll | |
history.push('/tab/1', { resetScroll: false }); // Don't reset the scroll |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// 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