React Router scroll page to the top after transition

Viewed 6444

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.

2 Answers

Can you try the below

 <BrowserRouter >        
    <Layout>
      <ScrollToTop />
        <Switch>
          <Route path="/" exact component={MainPageConfig} />
        </Switch>
    </Layout>
  </BrowserRouter>
import { useEffect } from "react";
import { useLocation } from "react-router-dom";

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

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

  return <>{children}</>;
}

just pass children down the tree

Related