React: Scroll To The Top of The Page

Abidemi Animashaun
3 min readJul 29, 2021

In this article, i’m going to briefly summarize how to create a button that smoothly scrolls back to the top of the page.

The simple concept to achieve it is enumerated and solved below.

  1. The scroll to top button is positioned at the bottom-right of the screen and hidden by default
  2. When the user scroll to a specific viewport, the button is visible
  3. When the user clicks the button, it scrolls back to the top of the page

Let’s get started to the nitty gritty.

Scroll to top using React functional Component and React hook

There are different ways and methods to achieve it, but i’m writing this article base on my own understanding and methods that works for me. I’ll also be using antd package for the icon. Feel free to create other methods that works for you.

Here are the steps to create scroll to top button.

Let’s set-up our component.

Step 1: Create a file and name it scroll-to-top.js

scroll-to-top.js

Step 2: Create a css file and name it scroll-to-top.css

scroll-to-top.css
scroll-to-top.css with animation property
scroll-to-top.css

Step 3: Install antd package by running npm install antd and import to App.js file to use it globally.

import antd to App.js

Step 4: Here is the main logic

  1. useState: useState accepts the initial value of the state variable which is a boolean set to false in this case. The current value of the state has been called visible and a method that can update the state variable has been called as setVisible.
useState

2. toggleVisibility(): This method checks the scroll position and updates the state. When the page is scroll to a specific position, say 170px the visibility state of our button changed to true.

3. useEffect: this method is invoked after our component is rendered and execute a return clean up function.

useEffect

4. scrollToTop(): This method scrolls the page back to the top smoothly.

scrollToTop method

5. Render(): Finally, apply all that method to the button element.

render method

Step 5: Now import this component globally in the header or footer component.

--

--

Abidemi Animashaun

Hi everyone! I’m a web full stack developer. I write JavaScript and Php with exemplary knowledge in Reactjs, Node.js, Laravel and Nest.js.