For react-router v4, here is a create-react-app that achieves the scroll restoration: http://router-scroll-top.surge.sh/.
To achieve this you can create decorate the Route
component and leverage lifecycle methods:
componentDidUpdate
On the path
we can check when the location App.jsname changes and match it to the path
prop and, if those satisfied, restore the window scroll.
What is cool about this approach, is that we can have routes that restore scroll and routes that don't restore scroll.
Here is an import React, { Component } from 'react'; import { BrowserRouter as Router, Route, Link } from 'react-router-dom'; import Lorem from 'react-lorem-component'; import ScrollToTopRoute from './ScrollToTopRoute'; import './App.css'; const Home = () => ( <div className="App-page"> <h2>Home</h2> <Lorem count={12} seed={12} /> </div> ); const About = () => ( <div className="App-page"> <h2>About</h2> <Lorem count={30} seed={4} /> </div> ); const AnotherPage = () => ( <div className="App-page"> <h2>This is just Another Page</h2> <Lorem count={12} seed={45} /> </div> ); class App extends Component { render() { return ( <Router> <div className="App"> <div className="App-header"> <ul className="App-nav"> <li><Link to="/">Home</Link></li> <li><Link to="/about">About</Link></li> <li><Link to="/another-page">Another Page</Link></li> </ul> </div> <Route exact path="/" component={Home} /> <ScrollToTopRoute path="/about" component={About} /> <ScrollToTopRoute path="/another-page" component={AnotherPage} /> </div> </Router> ); } } export default App;
example of how you can use the above:
/about
From the code above, what is interesting to point out is that only when navigating to /another-page
or /
the scroll to top action will be preformed. However when going on /
no scroll restore will happen.
The whole codebase can be found here: https://github.com/rizedr/react-router-scroll-top