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.

Related Blogs

Can't Perform a React State Update on an Unmounted Component

Can't Perform a React State Update on an Unmounted Component

React Warning “Can't perform a react state update on an unmounted component” is caused when we try to update the state after the component was unmounted. Explains how to fix it.

Each child in a list should have a unique key prop

Each child in a list should have a unique key prop

Solve Warning: Each child in a list should have a unique ”key" prop in React by setting the id property as a unique key or by auto-assigning unique keys.

React Hook is Called Conditionally

React Hook is Called Conditionally

Error: "React Hook is called conditionally. React Hooks must be called in the exact same order in every component render" occurs when hooks are invoked conditionally or after a return of a value.

Too many re-renders. React limits the number of renders to prevent an infinite loop

Too many re-renders. React limits the number of renders to prevent an infinite loop

The React error "Too many re-renders. React limits the number of renders to prevent an infinite loop" happens when you have reached an infinite render loop.

Adjacent JSX elements must be wrapped in an enclosing tag

Adjacent JSX elements must be wrapped in an enclosing tag

The "Adjacent JSX elements must be wrapped in an enclosing tag" error can be solved by wrapping the multiple elements in a parent div or in a react fragment

The tag is unrecognized in this browser

Warning: The tag is unrecognized in this browser

Warning "The tag is unrecognized in this browser" occurs when the tag doesn't exist in the browser or when we render a component starting with a lowercase letter.

The style prop expects a mapping from style properties to values, not a string

The style prop expects a mapping from style properties to values, not a string

"The style prop expects a mapping from style properties to values, not a string" React error occurs when we pass a CSS string to the style attribute.

Pass event and parameter onClick in React

How to pass event and parameter onClick in React

We set the inline arrow function (event) => clickHandler(event, "Hello World!") as props to the onClick event handler in the button. The arrow function takes the event as an argument and calls the clickHandler function.

Create a Back button with React Router

Create a Back button with React Router

To create a back button with React Router use useNavigate() hook. Call navigate function eg. navigate(-1); inside the onClick function of the back button.