DEV Community

Cover image for How to create a dynamic `scrollToTop` button in React! No library necessary! EVER
Chris Hansen
Chris Hansen

Posted on

How to create a dynamic `scrollToTop` button in React! No library necessary! EVER

Hey devs πŸ‘‹

Have you always wanted to know how to get that buttery smooth scroll back to top button!?

Ya don't need another library to achieve this! Get the job done in just a few minutes with some basic logic and javascript!


This is a speedcode tutorial, and I'll assume you have some working knowledge of:

  • React
  • Good concept of CSS or SASS
  • Not necessary, but I'll be using Styled-components ( CSS in JS library )


  1. React
  2. React Icons
  3. Styled-Components

Speedcode tutorial ‡️


Thats it for "How to create a dynamic scrollToTop button in React! No library necessary! EVER" I hope you enjoyed the video, and hope you never have to use another scroll button library again! Once you get the hang of the code, you'll be able to add this to your website in just a couple minutes, no doubt about it! #happycoding!

Additional resources you may enjoy!

Discussion (2)

lukeshiru profile image

For folks that want a written version the TL;DW:

<button onClick={() => window.scrollTo({ top: 0, behavior: "smooth" })}>
    Go to top
Enter fullscreen mode Exit fullscreen mode

You could track the scroll position of the window with the scroll event on a useEffect (which you should debounce). And you could also change that hardcoded 0 to whatever value makes sense for your app.


hyggedev profile image
Chris Hansen Author

Sweet, thanks for that input! I've been looking into browser performance best practices but I'm still trying to get better at the basics of react! I'll look into this though πŸ’―