Scroll to the top of the page after render in ReactJS

Today we will show you how to scroll to the top of the page after render in ReactJS. In other words, When you are redirecting from one route to the other route at that time might be you need “scroll to the top” because of the long content page. So we will show you how to do it.

Scroll to the top of the page after render in ReactJS, react-router-dom scroll to top, react scroll to top on route change, react scroll to element after render, window.scrollto(0 0) not working react, react scroll to bottom after render, Scroll Restoration – React Router, Scrolling to top on component render.

Issue:

In the react component I display a long list of data and a few links at the bottom. After clicking on any of these links I fill in the list with a new collection of links and need to scroll to the top.
The problem is – how to scroll to the top after a new collection is rendered?

Steps to implement scroll to the top of the page after render in ReactJS

  1. Set up react application
  2. Create top level component to manage the scroll
  3. Wrap scroll component to the application
  4. Output

1. Set up react application

Let’s create the react application and implement routing in application for the redirection purpose. If you don’t know how to create a routing in react app then refer to the following link.

Routing in React JS

2. Create top level component to manage the scroll

Now let’s create a component as ScrollToTop where we will listen to the history and set window scroll to top on componentDidMount. You can also ignore the routes for scroll to the top as well. Here we are using the React Hooks to manage the scroll position.

ScrollToTop.js

NOTE: Make sure you have a react-router-dom version is greater than 5.1 to use useLocation.

3. Wrap scroll component to the application

At last we need to set the ScrollToTop component at the top level of the application.

4. Output

Output - Scroll to the top of the page after render in ReactJS - Clue Mediator
Output – Scroll to the top of the page after render in ReactJS – Clue Mediator

Thank you for reading! Happy Coding!

Demo & Source Code

Github Repository StackBlitz Project
If you found value in this article,
you can support us by buying me a coffee! ☕

You may also like...

2 Responses

Leave a Reply

Your email address will not be published. Required fields are marked *