Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Scroll to top when using Switch (react-router)

When navigating from one page to another, I would like the user to be automatically scrolled to the top, i.e. scrollTo(0, 0).

According to the react-router docs on scroll restoration the recommended approach is to setup a component ScrollToTop and wrap your routes within this.

While this works well and the user is scrolled to the top for any route nested within the ScrollToTop component, if the component is placed within a Switch component, the Switch does not function like a Switch any longer; meaning that it will render all routes that it matches instead of the first one.

Alternatively, placing the ScrollToTop outside of the Switch, it no longer scrolls the user to the top.

Version: react-router-v4

like image 692
Kevin Farrugia Avatar asked Oct 21 '17 21:10

Kevin Farrugia


People also ask

How do I auto scrollTo top in react?

Use the window. scrollTo() method to scroll to the top of the page in React, e.g. window. scrollTo(0, 0) .

How do I change the scroll position in react?

To get scroll position with React, we can add a scroll listener to window . to create the scrollPosition state with the useState hook. Then we add the handleScroll function that takes the scroll position with the window.

How do I navigate in dom react router?

There are two ways to programmatically navigate with React Router - <Navigate /> and navigate() . You can get access to Navigate by importing it from the react-router-dom package and you can get access to navigate by using the custom useNavigate Hook.


1 Answers

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

const browserHistory = createBrowserHistory();

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

<Router history={browserHistory} />
like image 112
Austin Greco Avatar answered Oct 19 '22 23:10

Austin Greco