Dynamic Scroll To Top in React.js with react-router-dom and react hooks

Akash Kumar Seth
2 min readMay 1, 2019

--

Handling the scroll position in a react app on route change is a bit tricky. Since there is no default solution provided by the react-router-dom package I decided to tackle this issue.

While managing scroll position I have focused on three important cases and general required behavior.

Case:- When the user clicks on the Links to change the route. In this case, we generally require a scroll position is at top of the page.

Case 2:- When the user uses a back/forward button to change the route. In this case, we generally require that the scroll position be preserved as when previously visited.

Case 3:- When the route contains the hash value in route. In this case, we generally need the new page scroll position should be set according to the hash value.

Solution

I have created a react component “DynamicScrollToTop” to tackle this problem.

How to Use

Just render the “DynamicScrollToTop” where needed.

People.js File from one of my projects.

Hope this will also help others.

Thank you.

--

--