How to scroll to the top while using react-router-dom

singhanuj620

Anuj Singh

Posted on March 7, 2021

How to scroll to the top while using react-router-dom

Hey ✌✌

PROBLEM TO BE SOLVED 🤷‍♀️🤷‍♀️🤷‍♀️🤷‍♀️🤷‍♀️:

When we use react-router-dom library for routing pages and links in the react project, the problem with it is that when clicked on an Link the next component rendered does not get started from the top of the page, instead it renders the page from the scroll height of the parent component i.e the component which holds the Link tag.

So, what we are going to do is to render the new component/page/route from top of the scroll height, not from in-between.

SOLUTION 😎😎😎😎 :

Make a new File just like other component file - Let us name it ScrollToTop.js

import React, { Component } from "react";
import { withRouter } from "react-router-dom";
class ScrollToTop extends Component {
  componentDidUpdate(prevProps) {
    if (this.props.location !== prevProps.location) {
      window.scrollTo(0, 0);
    }
  }
  render() {
    return <React.Fragment />;
  }
}
export default withRouter(ScrollToTop); 
Enter fullscreen mode Exit fullscreen mode

Now add this file as a normal component to just below the tag like this :

Screenshot

💖 💪 🙅 🚩
singhanuj620
Anuj Singh

Posted on March 7, 2021

Join Our Newsletter. No Spam, Only the good stuff.

Sign up to receive the latest update from our blog.

Related