Reset Scroll position on change of Routes — React
I am working with ReactJS from a while. During this time I am working a project where I found a common issue of React-router. I am working to create front-end of a website with ReactJS. The site contains long pages including homepage. The issue was when we scrolled to the bottom and click on any links or menu item to route another page, the next page always on the previous page scroll position. That’s really annoying. That isn’t ideal behavior as the user expects to go to the top of the page. So let’s look at how I resolved the issue.
The above is an example of a router for a project I am putting together. With this router setup, whenver we scroll to bottom of home page and navigate to other page like About route, I remain at the same scroll position from the Home route.
We can change the page scroll position with this js code snippet. window.scrollTo(0,0)
We can achive the behaviour with react history api.
Lets make an update to our history to like this
We can add those line to our App.jsx after creating history to update our experience when navigate between routes.
So with this update, whenever history API listen any change in router path, the window’s scroll position is reset to 0,0 providing the expected behavior for the user.
I am open to other suggestions to address this issue. I am always interested in feedback.