scroll to top on react react-router-dom page change

I’m using react-router-dom for implementing routing of my reactjs App!
but I have an issue with this , in which I can’t find any working solution for scroll to top on page changing. can any body help me???

here is my routing piece of code:

    <BrowserRouter  basename={basename}> 
          <Switch>
                    <MobilePage hasNav navType="primary" exact path={`/restaurant`} component={VendorList} />
                    <MobilePage hasNav navType="primary" path={`/restaurant/:vendorCode`} component={VendorDetails} /> 
          </Switch>
    </BrowserRouter>

10 thoughts on “scroll to top on react react-router-dom page change”

  1. I am currently using the react-router-dom v5 (most of these solutions that I found was geared to v4) and I was surprised to not find a solution for pages to load to the top in a transition.

    What solved my problem was installing react-router-scroll-top and put the wrapper in the like this:

    const App = () => (
      <Router>
        <ScrollToTop>
          <App/>
        </ScrollToTop>
      </Router>
    )
    

    and everything worked as expected.

    Reply

Leave a Comment