Scroll up when using a switch (reaction router)

When moving from one page to another, I would like the user to automatically scroll up, i.e. scrollTo(0, 0).

According to react-router docs, when restoring a scroll, the recommended approach is to configure the component ScrollToTopand transfer your routes within that.

So far, this works well, and the user scrolls at the top for any route nested in the component ScrollToTop, if the component is placed in the component Switch, it Switchno longer works as a switch; this means that it will display all the routes that it maps, instead of the first.

Alternatively, by posting ScrollToTopout Switch, it no longer scrolls the user up.

Version: react-router-v4

+4
source share
3 answers

I'm not sure specifically about scrolling, but you can attach a listener to browserHistory, which may be an easy way to do this (I don't think it onUpdateworks with v4):

const browserHistory = createBrowserHistory();

browserHistory.listen((location, action) => {
  window.scrollTo(0, 0);
});

<Router history={browserHistory} />
+5
source

I had the same problem that I did. When updated, the user goes toscrollTo(0,0)

<Router onUpdate={() => window.scrollTo(0, 0)} history={createBrowserHistory()}>
  ...
</Router

If the above does not work:

In reaction-router-v4 scroll recovery

, , Router, :

 componentDidUpdate(prevProps) {
    if (this.props.location !== prevProps.location) {
      window.scrollTo(0, 0)
    }
  }

  render() {
    return this.props.children
  }
}

, Router

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

React-Router -

+1

I managed to solve this with react-router-v4scroll Restoration and putting ScrollToTop outside Switch. Also remember to use withRouter, otherwise it will not work.

+1
source

Source: https://habr.com/ru/post/1687957/


All Articles