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
Use the window. scrollTo() method to scroll to the top of the page in React, e.g. window. scrollTo(0, 0) .
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.
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.
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} />
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With