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.
- The scroll to top button is positioned at the bottom-right of the screen and hidden by default
- When the user scroll to a specific viewport, the button is visible
- 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
Step 2: Create a css file and name it scroll-to-top.css
Step 3: Install antd package by running npm install antd and import to App.js file to use it globally.
Step 4: Here is the main logic
- 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.
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.
4. scrollToTop(): This method scrolls the page back to the top smoothly.
5. Render(): Finally, apply all that method to the button element.
Step 5: Now import this component globally in the header or footer component.