DEV Community

Cover image for How to scroll to the top while using react-router-dom
Anuj Singh
Anuj Singh

Posted on

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

Top comments (0)