最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - scroll to top on react react-router-dom page change - Stack Overflow

programmeradmin7浏览0评论

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`} ponent={VendorList} />
                    <MobilePage hasNav navType="primary" path={`/restaurant/:vendorCode`} ponent={VendorDetails} /> 
          </Switch>
    </BrowserRouter>

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`} ponent={VendorList} />
                    <MobilePage hasNav navType="primary" path={`/restaurant/:vendorCode`} ponent={VendorDetails} /> 
          </Switch>
    </BrowserRouter>
Share Improve this question asked Jun 24, 2018 at 10:43 MohammadJavad SeyyediMohammadJavad Seyyedi 6847 silver badges21 bronze badges
Add a ment  | 

3 Answers 3

Reset to default 5

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.

add to VendorList and VendorDetails in ponentDidMount() function window.scrollTo(0,0)

Install the plugin below https://www.npmjs./package/react-router-scroll-top

import ScrollToTop from 'react-router-scroll-top'

const App = () => (
<Router>
  <ScrollToTop>
     <App/>
  </ScrollToTop>
</Router>
  )
<ScrollToTop/>
发布评论

评论列表(0)

  1. 暂无评论