Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Restore scroll position when navigating with React Router 6

How do I set up React Router 6 to restore scroll position when I navigate and when the browser window is refreshed?

React Router 5 has a page about scroll restoration, but I can't find anything about scrolling in the docs for v6, so I guess that you're supposed to handle this yourself with another package. Fair enough, but I can't find anything that's compatible with React Router 6.

The packages react-scroll-restoration and oaf-react-router require v5. (oaf-react-router does list that it supports v6, but the basic usage code example isn't compatible with v6, and the related issue #210 is still open.)

Gatsby and Next.js support scroll restoration out of the box, but I doesn't look like there's a neatly packaged package that you can just use.

This little demo app with server side rendered pages does what I want. Scroll position is restored when navigation back and forth and refreshing the browser window.

Here is the same app using React Router 6, where the scroll position isn't saved and restored, but actually reused between pages. The usual workaround for that is to scroll to the top whenever the page is navigated, but I am not interested in that behaviour.

Edit: React Query writes that the issue with scroll restoration is that pages are refetching data, thereby implying that if the data for rendering the pages is there, scroll restoration just works. I cannot confirm that, because my small React Router 6 app has the issue even without doing any data fetching at all. I feel like there is something small think I am missing in order to get it to work.

Rant: I am quite surprised that the typical answer to this issue is to call window.scrollTo(0, 0) when navigating. This only fixes the issue of the scroll position being transferred between pages. When the scroll position isn't restored, the user experience when navigating between pages is seriously deteriorated. I guess this is partly why pop-up windows have become so popular, but they bring a long suite of other UX issues, so I really want to avoid using them.

like image 589
Jan Aagaard Avatar asked Jan 18 '26 07:01

Jan Aagaard


1 Answers

The ScrollRestoration component handles exactly this. It requires using a data router, such as one created by calling createBrowserRouter (which is recommended for all new React Router web projects).

This component will emulate the browser's scroll restoration on location changes after loaders have completed to ensure the scroll position is restored to the right spot, even across domains.

To use it, simply render it once in the application root component:

import { ScrollRestoration } from "react-router-dom";
function App() {
    return <>
        <div>Some content...</div>
        <ScrollRestoration/>
    </>;
}
like image 144
Unmitigated Avatar answered Jan 20 '26 20:01

Unmitigated