DEV Community

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

Posted on

2 2

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

Sentry image

Hands-on debugging session: instrument, monitor, and fix

Join Lazar for a hands-on session where you’ll build it, break it, debug it, and fix it. You’ll set up Sentry, track errors, use Session Replay and Tracing, and leverage some good ol’ AI to find and fix issues fast.

RSVP here β†’

Top comments (0)

A Workflow Copilot. Tailored to You.

Pieces.app image

Our desktop app, with its intelligent copilot, streamlines coding by generating snippets, extracting code from screenshots, and accelerating problem-solving.

Read the docs

πŸ‘‹ Kindness is contagious

Please leave a ❀️ or a friendly comment on this post if you found it helpful!

Okay