Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

React Router scroll page to the top after transition

In my application, when I change from one page to another the page is being kept at the same point it was on the previous page. I want to make it go to the top when I swap pages.

The react-router documentation has a solution: https://reactrouter.com/web/guides/scroll-restoration

I implemented it inside a component called ScrollToTop and wrapped my whole application with it, but everything inside it just don't get rendered. I have no idea why.

ScrollToTop:

import { useEffect } from "react";
import { useLocation } from "react-router-dom";

export default function ScrollToTop() {
  const { pathname } = useLocation();

  useEffect(() => {
    window.scrollTo(0, 0);
  }, [pathname]);

  return null;
}

App:

import React from 'react';

import './App.css';

import Layout from './containers/Layout/Layout'
import MainPageConfig from './containers/MainPageConfig/MainPageConfig'

import ScrollToTop from './HOC/ScrollToTop'

import { BrowserRouter, Route, Switch } from 'react-router-dom'


function App() {
  return (
    
      <BrowserRouter >        
        <Layout>
          <ScrollToTop>
            <Switch>
              <Route path="/" exact component={MainPageConfig} />
            </Switch>
          </ScrollToTop>
        </Layout>
      </BrowserRouter>
    
    
  );
}

export default App;

I also tried the suggestions of this post: react-router scroll to top on every transition

In both cases I get the same result.

How could I solve this?

P.S. I also tried to put ScrollToTop outside Layout, but nothing changes.

like image 521
Berg_Durden Avatar asked Jan 20 '26 00:01

Berg_Durden


2 Answers

Can you try the below

 <BrowserRouter >        
    <Layout>
      <ScrollToTop />
        <Switch>
          <Route path="/" exact component={MainPageConfig} />
        </Switch>
    </Layout>
  </BrowserRouter>
like image 155
Rain.To Avatar answered Jan 21 '26 14:01

Rain.To


Since React Router 6.4, the ScrollRestoration component can be used to scroll to the top after navigating to a new page (as well as restoring the old scroll position on returning to a previous page). 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.

Render ScrollRestoration once in the application's root route component to use it:

import { ScrollRestoration } from "react-router-dom";
function App() {
    return <>
        { /* content here... */ }
        <ScrollRestoration />
    </>;
}
like image 30
Unmitigated Avatar answered Jan 21 '26 13:01

Unmitigated