As I delve deeper into React I want to continue writing about issues I hit or just just little tips I have come across. In this post I will be covering how to reset the window's scroll position top the top as the user changes routes.

An issue that I have found common amongst single page apps (SPAs) is when scrolling to the bottom of a longer page, for example a blog posting, and then you navigate away to another page, the user remains at the current scroll position from the original page. That isn't ideal behavior as the user expects to go to the top of the page. So let's look at how this can be resolved.

  ReactDOM.render((
    <Router history={browserHistory}>
        <Route path='/' component={App}>
            <IndexRoute component={Home}></IndexRoute>
            <Route path="/about" component={About}/>
            <Route path="/work">
                <IndexRoute component={Work}></IndexRoute>
                <Route path=":id" component={ProjectFull}></Route>
            </Route>
            <Route path="/blog" component={Blog}/>
        </Route>
    </Router>
), document.getElementById('root'));

The above is an example of a router for a project I am putting together. With this router setup, whenever I scroll to the bottom of the blog route and then navigate to the about route, I remain at that scroll position from the blog route.

Let's make an update to our router to address this:

onUpdate={() => window.scrollTo(0, 0)}

We can add the previous line to our router to update our experience when navigating between routes.

  ReactDOM.render((
    <Router onUpdate={() => window.scrollTo(0, 0)} history={browserHistory}>
        <Route path='/' component={App}>
            <IndexRoute component={Home}></IndexRoute>
            <Route path="/about" component={About}/>
            <Route path="/work">
                <IndexRoute component={Work}></IndexRoute>
                <Route path=":id" component={ProjectFull}></Route>
            </Route>
            <Route path="/blog" component={Blog}/>
        </Route>
    </Router>
), document.getElementById('root'));

So with this update, whenever an onUpdate event is triggered, the window's scroll position is reset to 0,0 providing the expected behavior for the user.

Again, like my last React post, I am open to other suggestions to address this issue. Is this solution breaking convention in React? I'm always interested in feedback.