Monday, May 20, 2024
 Popular · Latest · Hot · Upcoming
68
rated 0 times [  74] [ 6]  / answers: 1 / hits: 8430  / 4 Years ago, wed, october 14, 2020, 12:00:00

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.


More From » reactjs

 Answers
6

Can you try the below


 <BrowserRouter >        
<Layout>
<ScrollToTop />
<Switch>
<Route path="/" exact component={MainPageConfig} />
</Switch>
</Layout>
</BrowserRouter>

[#2486] Sunday, October 11, 2020, 4 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
janjadonb

Total Points: 4
Total Questions: 114
Total Answers: 118

Location: Mali
Member since Fri, Dec 3, 2021
3 Years ago
janjadonb questions
Tue, Nov 10, 20, 00:00, 4 Years ago
Tue, Apr 14, 20, 00:00, 4 Years ago
Thu, Mar 19, 20, 00:00, 4 Years ago
;