How to React scroll to top on click?


How to go on the top of the page when click on the any navigation or the button?

React render work only one time when go to on the but he is not go on the top of the page and you will see your page content where your pointer was available before and your router url will be changed and you don’t feel that you have changed your page content. So we need to go to the top of the page with the below code:

React-router scroll to top on every transition.
This is for the stateless component:
React.useEffect(() => {
    window.scrollTo(0, 0);
  }, [props.location]);

This is for the class based component.
componentDidUpdate() {
  window.scrollTo(0,0);
}

If you are using "Router" tag then you can use it as below code:
<Router onUpdate={() => window.scrollTo(0, 0)} history={createBrowserHistory()}>
  ...
</Router>


No comments:

Note: Only a member of this blog may post a comment.

Copyright Reserved to Anything Learn. Powered by Blogger.