With React Router v4 & v5
, the smooth scroll restoration in SPA
I experiencing some problems with scroll positions on the back button (History Popstate) when using react-router.
In a single page application (SPA), the application manipulates the browser history and DOM to simulate navigation. Because navigation is simulated and rendering is dynamic, the usual browser behavior of restoring scroll position when navigating back and forth through the history is not generally functional
React Router does not provide out of the box support for scroll restoration and as it currently stands they won't either, because browsers are implementing some automatic scroll behavior
history.scrollRestoration
API is just a way of disabling the browser's automatic attempts at scroll restoration, which mostly don't work for SPA
# yarn
yarn add react-scroll-restoration
# npm
npm install react-scroll-restoration
import React from 'react';
import { BrowserRouter as Router, Switch } from 'react-router-dom';
import ScrollRestoration from 'react-scroll-restoration'
function App() {
return (
<Router>
<ScrollRestoration />
<Switch>
<Route />
<Route />
</Switch>
</Router>
);
}