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.
Can you try the below
<BrowserRouter >
<Layout>
<ScrollToTop />
<Switch>
<Route path="/" exact component={MainPageConfig} />
</Switch>
</Layout>
</BrowserRouter>
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 />
</>;
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With