How to Scroll to Top in React

Rana Hasnain Khan Feb 02, 2024
How to Scroll to Top in React

We will introduce how to create a button with scrolling to the top of the page functionality in React.

Use the react-scroll-to-top Library to Create Scroll to Top Button in React

When we have a lot of content on a single page, it is difficult for users to scroll to reach the top to see navigation or navigate to another page. But as a developer, we always find ways to make life easy for users to scroll to the top with just one button click.

If we try to build a scroll to top button will all functionality, we may have to write a little bit of code. But when we are working on a React application, we can achieve this functionality by installing a library that was made to make our life easier.

Let’s go through an example to scroll to the top with just a button.

A library called react-scroll-to-top is used to get the scroll-to-top functionality. So let’s create a new application in React by using the following command.

# react
npx create-react-app my-app

After creating our new application in React, we will go to our application directory using this command.

# react
cd my-app

Now, let’s run our app to check if all dependencies are installed correctly.

# react
npm start

Now, let’s install the library react-scroll-to-top using npm.

# react
npm i react-scroll-to-top

Once the library is installed, we can now import the ScrollToTop in our App.js.

# react
import ScrollToTop from "react-scroll-to-top";

Now, inside our default function, we will return a template that will cover around 200vh of the page to achieve a scroll to the top. We will also return the ScrollToTop component with some settings such as smooth for smooth scrolling and color to set the icon’s color.

So our code in App.js will look like below.

# react
import React from "react";
import "./styles.css";
import ScrollToTop from "react-scroll-to-top";

export default function App() {
  return (
    <div className="App">
      <ScrollToTop smooth color="#000" />
      <h1>Scroll To See Magic</h1>
      <p style={{ marginTop: "200vh" }}>You Have Reached Bottom</p>
    </div>
  );
}

Now, let’s check how our application works.

Output:

scroll to top function in react

As you notice in the image above, we have successfully created a scroll to top animation by adding a single line of code in our application.

In this way, we can use the scroll to top function on any of our pages without writing more than one line of code.

Rana Hasnain Khan avatar Rana Hasnain Khan avatar

Rana is a computer science graduate passionate about helping people to build and diagnose scalable web application problems and problems developers face across the full-stack.

LinkedIn

Related Article - React Scroll