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);
Now add this file as a normal component to just below the tag like this :
Top comments (0)