scroll

A React component that scrolls to the top of a page

Apr 13, 2021
A React component that scrolls to the top of a page

react-router-scroll-to-top

ScrollToTop is a React component that scrolls to the top of a page when the current location gets changed. Since React Router doesn't provide out-of-the-box support for scroll restoration due to browsers having started handling it on their own, this package implements a component for scrolling to the top manually as it is given in React Router docs.

View Demo View Github

## Installing

  • npm:
npm install react-router-scroll-to-top
  • yarn:
yarn add react-router-scroll-to-top

This package works only in versions of React that support hooks.

Import

From the package you can import:

  • a hook that activates scrolling to the top of a page on redirect:
import { useScrollToTop } from 'react-router-scroll-to-top';
  • a component that just runs the hook under the hood:
import { ScrollToTop } from 'react-router-scroll-to-top';

Setting up

  • with a hook:
const App = () => { useScrollToTop(); return <Switch>{/* routes */}</Switch>; };

An important note: don't use this hook in a component with a router (BrowserRouter, MemoryRouter, etc.).

  • with a component (can be used in a component with a router):
const App = () => ( <BrowserRouter> <ScrollToTop /> <Switch>{/* routes */}</Switch> </BrowserRouter> );

or

const App = () => ( <BrowserRouter> <ScrollToTop> <Switch>{/* routes */}</Switch> </ScrollToTop> </BrowserRouter> );

Usage

That's it. The package doesn't demand you to do anything else. Just keep using react-router-dom as before.

If in some cases you need to disable scrolling to the top of a page, pass { scrollToTop: false } to the state:

<Link to={{ pathname: '/any-page', state: { scrollToTop: false } }}> Any page </Link>
const { push } = useHistory(); push('/any-page', { scrollToTop: false });

GitHub

https://github.com/dimazuien/react-router-scroll-to-top

Recommended