How to create a scroll to top button in React

To create a scroll to top button in React, follow the below steps.

  1. Create and style a button.
  2. Implement the button visibility logic with useState and useEffect hook.
  3. Handle the scroll to the top action.

The scroll to top is a good feature on many websites which enables users to run to the top without having to scroll anymore.

In this tutorial, we are going to create a scroll to the top button in React. It is a customizable ScrollToTop component created from scratch using React hooks and window objects. This is a separate component and it can be reused in other React projects in the future.

Create and style a button

The first step is to create a button, add style, and fix it in the right bottom position of the page. 

We will be using the up-arrow from react-icons npm package in this tutorial. You can use any other icon or image instead of it.

For installing react-icons run the below command:

npm install --save react-icons

Next Import the library into the ScrollToTop component.

import React from 'react';
import { FaArrowCircleUp } from 'react-icons/fa';
import './ScrollToTop.css';

const ScrollToTop = () => {
    return (
        <button className="btn-scrollTop">
            <FaArrowCircleUp/>
        </button>
    );
}

export default ScrollToTop;

Add styles to the ScrollToTop.css file.

.btn-scrollTop{
    position: fixed;
    bottom: 40px;
    font-size: 3rem;
    z-index: 1;
    cursor: pointer;
    color: green;
    right: 2%;
    background: none;
    border-radius: 50px;
    padding: 0px;
    border: none;
    opacity: 0.7;
}

Implement the button visibility logic with useState and useEffect hook

The scroll to top button should only be shown when the user scrolls the page down a bit and hidden after the user has scrolled to the top. We are going to implement this logic with the help of useState and useEffect hooks and event listeners.

Next, create a state isVisible to control the visibility of the button and its initial state will be false.

const [isVisible, setIsVisible] = useState(false)

When the user scrolls the page a little bit the isVisible state will be changed to true by event listener as in the given below code.

useEffect(() => {
	window.addEventListener('scroll', () => {
		if (window.scrollY > 100) {
			setIsVisible(true);
		} else {
			setIsVisible(false);
		}
	});
 }, []);

We added an event listener to our window that will listen for the scroll event of the page. The window.scrollY gives us the vertical scroll position of the page. If the vertical scroll position is greater than 100, then isVisible state will be set to true

For the conditionally displaying button, we checked isVisible state in the button display style with a ternary operator as given below.

<button className="btn-scrollTop" style={{display: isVisible ? 'block':'none'}}>
	<FaArrowCircleUp/>
</button>

Handle the scroll to the top action

The next step is to implement the scroll to top action on the button click. 

const goTop = () => {
	window.scrollTo({
		top: 0,
		behavior: 'smooth',
	});
};    

For scrolling, we are used scrollTo() method of window object. In the above code, top: 0 determine which position it is scrolled.

Our final code will be:

// This is our final code
import React, { useState, useEffect } from 'react';
import { FaArrowCircleUp } from 'react-icons/fa';
import './ScrollToTop.css';

const ScrollToTop = () => {
    const [isVisible, setIsVisible] = useState(false);

    useEffect(() => {
        window.addEventListener('scroll', () => {
            if (window.scrollY > 100) {
                setIsVisible(true);
            } else {
                setIsVisible(false);
            }
        });
    }, []);

    const goTop = () => {
        window.scrollTo({
            top: 0,
            behavior: 'smooth',
        });
    };

    return (
        <button className="btn-scrollTop" style={{display: isVisible ? 'block':'none'}} onClick={goTop}>
            <FaArrowCircleUp/>
        </button>
    );
}

export default ScrollToTop;

We can import the ScrollToTop component into any react pages and can use it as given below. In this tutorial, we going to import and add it on App component. You can add it to any page in the application.

import React from 'react';
import  ScrollToTop from './ScrollToTop';

export default function App() {
  	return (
    	<>  
      		<div>Some content here.</div>      
      		<ScrollToTop/>          
    	</>
  	);
}

If you are going to implement scroll to top in all react pages, then it is better to add it in the layout file.

Conclusion

In this tutorial, we have learned how to create a scroll to top button in React from scratch. It is easily customizable and can be reused in many react projects. We have react-icons as a dependency for this component. You can use your own icons for the buttons.