Scroll To Top Button using React

Danilo Rivera
2 min readDec 29, 2020

--

In several Ecommerces, blogs we see the function of an infinite scroll but suddenly we get bored of going down.

then the problem is to return to the top, we must make a gigantic scroll or in the case of the mobile it becomes heavier.

the simple solution: a scroll to top button.
simple, effective and that can work in our ecommerce, blogs, etc.

Scroll to Top

let’s install our dependencies first

yarn add react-icons

yarn add styled-components

our component GoToTop will look like this

Window.OnScroll: This DOM function detects when the window scrolls.
in this way we can call an event when a scroll happens.

scrollFunction: document.body.scrollTop,get the number of pixels the content of a <div> element is scrolled horizontally and vertically.

in this case I chose that it was higher than 760 that way the button could be displayed when it is scrolling and it has exceeded 3 rows

then as I have this component in my root, I decided to do a little validation to prevent something from going wrong, then if the button exists in the dom, I hide it or show it depending on the vertically traveled pixels.

scrollTopFunction: this function is the one that will do the magic of taking us up, the important thing here is the smoth property, if you ignore it nothing will fail, but the effect will be too abrupt for the user.

now just call the component on your root like this

ready, you already have your button working, it will look spectacular especially when your site is visited on mobile

Final Result

Like always complete Code Here:

--

--