Please note that history.scrollRestoration is just a way to turn off automatic scrolling recovery attempts in the browser, which basically do not work for single-page applications so that they do not interfere with the application. In addition to switching to manual recovery by scrolling, you will need some kind of library that provides integration between the browser history API, React rendering and the window's scroll position and any elements of the scrollable block.
After I could not find such a scroll recovery library for React Router 4, I created one of them, called the react-scroll-manager . It supports scrolling to the top when moving to a new place (also known as a push of history) and restoring scroll back / forward (also known as history). In addition to scrolling the window, it can scroll any nested element that you transfer to the ElementScroller component. It also supports deferred / asynchronous rendering using MutationObserver to view the contents of a window / element up to a user-specified time limit. This support for deferred rendering applies to scrolling restoration, as well as scrolling to a specific element using a hash link.
npm install react-scroll-manager
import React from 'react'; import { Router } from 'react-router-dom'; import { ScrollManager, WindowScroller, ElementScroller } from 'react-scroll-manager'; import { createBrowserHistory as createHistory } from 'history'; class App extends React.Component { constructor() { super(); this.history = createHistory(); } render() { return ( <ScrollManager history={this.history}> <Router history={this.history}> <WindowScroller> <ElementScroller scrollKey="nav"> <div className="nav"> ... </div> </ElementScroller> <div className="content"> ... </div> </WindowScroller> </Router> </ScrollManager> ); } }
Note that HTML5 (10+ for IE) and React 16 are required. HTML5 provides a history API, and the library uses the modern Context and Ref APIs from React 16.
Trevor robinson
source share