Skip to content

Instantly share code, notes, and snippets.

@luke-john
Created February 13, 2017 05:13
Show Gist options
  • Save luke-john/31496dadf97b8b753ca3dc4b052e1c2b to your computer and use it in GitHub Desktop.
Save luke-john/31496dadf97b8b753ca3dc4b052e1c2b to your computer and use it in GitHub Desktop.
scroll on nav
import ScrollOnNav from 'components/ScrollOnNav'
...
const render = () => {
ReactDOM.render(
(
<BrowserRouter>
<ScrollOnNav>
<App />
</ScrollOnNav>
</BrowserRouter>
),
container,
)
}
...
import * as React from 'react'
interface Context {
history: any
}
class ScrollOnNav extends React.Component<{}, any> {
static contextTypes = {
history: React.PropTypes.object,
}
lastLocation = ''
componentWillReceiveProps(_: {}, nextContext: Context) {
if (this.pathChanged(this.lastLocation, nextContext)) {
this.lastLocation = nextContext.history.location.pathname
window.scrollTo(0, 0)
}
}
pathChanged(lastLocation: string, nextContext: Context) {
return lastLocation !== nextContext.history.location.pathname
}
render() {
return React.Children.only(this.props.children)
}
}
export default ScrollOnNav
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment