Why react-router-dom scroll to top is not working?

Viewed 107

I´ve been having this issue that when I have a long content page, that when navigated to, stays scrolled down, so I needed a way to scroll the window up on every navigation. I´ve researched on google and even used the react-router-dom documentation component but nothing has worked so far.

I´d be glad to get some clue on how I can solve this.

Thanks!

  • ScrollToTop Component
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.js Component
function App() {
  return (
    <>
      <Router>
        <NavBar />
        <ScrollToTop />

        <Switch>
          <Route exact path="/" component={MainPage} />
          <Route exact path="/contracts" component={ContractPage} />
          <Route exact path="/areas" component={AreasPage} />
          <Route exact path="/about" component={AboutPage} />
          <Route exact path="/gallery" component={GalleryPage} />
          <Route exact path="/get-a-quote" component={GetAQuotePage} />
          <Route
            exact
            path="/insulated-garden-room"
            component={GardenRoomPage}
          />
          <Route exact path="/erecting-fence" component={FencePage} />
          <Route
            exact
            path="/garden-storage-shed"
            component={GardenStoragePage}
          />
          <Route
            exact
            path="/bathroom-renovation"
            component={BathRenovationPage}
          />
          <Route exact path="/roof-cleaning" component={RoofCleaningPage} />
          <Route
            exact
            path="/painting-decoration"
            component={PaintingDecorationPage}
          />
          <Route
            exact
            path="/flooring-tiles-instalation"
            component={FlooringTilesPage}
          />
          <Route exact path="/eletical-services" component={EletricalPage} />
          <Route
            exact
            path="/heating-plumbing"
            component={HeatingPlumbingPage}
          />

          <Route component={NotFound} />
        </Switch>
        <Footer />
      </Router>

      <GlobalStyles />
    </>
  );
}
export default App

OBS: All routes are working fine.

0 Answers
Related