React Router Scroll Position
This library can correct the scroll position when changing routes. This means it can restore the scroll position to it's original state when moving backwards in the browser. It will also check for hash locations and find that element on the page to set the scroll position to that location. If none of the above apply, it will set the scroll position to 0 (top).
It's mostly usefull when working with animated routes, so that you can control when the scroll position should be set correctly.
Installation
Using NPM:
npm install react-router-scroll-position --save
Using Yarn:
yarn add react-router-scroll-position
How to use
Scroll restoration
Turn off scroll restoration for the best experience.
if ('scrollRestoration' in history) {
history.scrollRestoration = 'manual';
}
Fixed elements
To get the correct scroll position with fixed elements in mind (for example a sticky header), make sure you add a data-fixed
attribute to all elements that are fixed position and should be distracted for calculation of position.
<Header data-fixed />
Helper functions
Use the two helper functions provided by the library.
setScrollPosition
Used to set the scroll position when a route is mounted.
import { setScrollPosition } from 'react-router-scroll-position';
Accepts one argument:
componentDidMount() {
setScrollPosition(history);
}
storeScrollPosition
Used to store the scroll position when a route is unmounted.
Use this on the component with the Switch
from react-router (docs).
Make sure the component has access to the history object's properties, for instance by using withRouter
(docs).
import {
getScrollPosition,
storeScrollPosition,
} from 'react-router-scroll-position';
getSnapshotBeforeUpdate(prevProps, prevState) {
return getScrollPosition();
}
componentDidUpdate(prevProps, prevState, scrollTop) {
const { location } = prevProps;
storeScrollPosition(location, scrollTop);
}