React Router 4 scroll management
npm install react-router-scroll-4React Router scroll management.
react-router-scroll is a React Router component that adds scroll management using scroll-behavior. By default, the component adds browser-style scroll behavior, but you can customize it to scroll however you want on route transitions.
This is a fork of the original React Router scroll made to support Reat Router v4. Currently all the original features should be working but it is still in early development, tests have not been completely updated yet and there are probably bugs to be encountered. Do not hesitate to signal them, or fix them through pull requests.
``js
import { BrowserRouter } from 'react-router-dom';
import { ScrollContext } from 'react-router-scroll-4';
/ ... /
ReactDOM.render(
ScrollContext>
BrowserRouter>,
container
);
`
`shell`
$ yarn add react-router-scroll-4
Use the ScrollContext wrapper as in the example above. ScrollContext Should always have only one child, same as all the Router components.
You can override [scroll-behavior] by sending custom costructor through the property scrollBehavior to ScrollContext:
`js`
ScrollContext>
You can provide a custom shouldUpdateScroll as a property of ScrollContext. This function is called with the previous and the current router props. Those properties correspond to those accessible through withRouter.
The function can return:
- a falsy value to suppress updating the scroll position
- a position array of x and y, such as [0, 100], to scroll to that position
- a truthy value to emulate the browser default scroll behavior
`js
shouldUpdateScroll = (prevRouterProps, { location, history }) => (
prevRouterProps && location.pathname !== prevRouterProps.location.pathname
);
shouldUpdateScroll = (prevRouterProps, { location, history }) => {
if (history.action === 'POP') {
return false;
}
if (location.state["MY-USER-KEY"] === "NoScroll") {
return [0, 0];
}
return true;
};
`
Use in components rendered by a ScrollContext to manage the scroll behavior of elements other than window. Each must be given a unique scrollKey, and can be given an optional shouldUpdateScroll callback that behaves as above. ScrollContainer should have exactly one child, which will be the node managed.
`js
import { ScrollContainer } from 'react-router-scroll';
function Page() {
/ ... /
return (
shouldUpdateScroll={shouldUpdateScroll}
>
);
}
`
does not support on-the-fly changes to scrollKey or to the DOM node for its child.
#### Server side rendering
Both and