How to Smooth Scroll to Top On Button Click in React

Last updated on: by Digamber

React scroll to top button example; User experience is the primary reason that decides the future of your website. There are plenty of nuances that ensure your site’s usability. Modern websites display a ton of content by scrolling vertically on websites to consume content.

It will be a little bit awkward in modern apps to scroll back to the top. We can add a smooth scroll to the top button to resolve such a problem.

The Scroll to top button in React can take your users back to the top section of the site without deliberately scrolling.

This short tutorial will teach you how to create a dynamic scroll to the top button in React js application using a window.scrollTo, window.pageYOffse methods, useEffect, and useState hooks.

The useEffect hook tracks component rendering; it will calculate the pageYOffset and update the component state. It will help us create the Scroll to top functionality through the scrollTo method.

The window.scrollTo() method allows scrolling to a particular set of coordinates in the document.

It takes x-coord and y-coord parameters. The x-coord is the pixel along the horizontal axis of the document that you need to show in the upper left.

At the same time, the y-coord is the pixel along the vertical axis of the document that you need to show in the upper left. Moreover, it also takes options parameters that you can use to define top, left and behaviour properties.

Download New React Application

There is a simple straightforward way to create brand a new React project. Make sure to have node and npm installed on your system afterthat run the given command

npx create-react-app react-blog

Move toward the project folder, with given command.

cd react-blog

Create Component File

You need a new functional component, hence make the components/Profile.js file. Here is the basic structure of a functional component.

import React from 'react'
function Profile() {
  return (
    <div>Profile</div>
  )
}
export default Profile

Create Scroll to Top Button

You have to place the suggested code in the components/Profile.js file. We are using React hooks and the JavaScript methods to build the scroll to top button in React.

import React from "react";
const Profile = () => {
  const [scrollTop, setScrollTop] = React.useState(false);
  React.useEffect(() => {
    window.addEventListener("scroll", () => {
      if (window.pageYOffset > 340) {
        setScrollTop(true);
      } else {
        setScrollTop(false);
      }
    });
  }, []);
  const bottomToTop = () => {
    window.scrollTo({
      top: 0,
      behavior: "smooth",
    });
  };
  return (
    <>
      <div className="wrapper block-one"></div>
      <div className="wrapper block-two"></div>
      <div className="wrapper block-three"></div>
      <div className="wrapper block-four"></div>
      <div className="wrapper block-five"></div>
      {scrollTop && (
        <button onClick={bottomToTop} className="backToTop">
          &#8593;
        </button>
      )}
    </>
  );
};
export default Profile;

Add CSS to Style Scroll Top Button

We are not using any CSS framework to style the component; write some custom CSS to style the component therefore add the code to the src/App.css file.

.backToTop {
  bottom: 25px;
  right: 25px;
  position: fixed;
  font-size: 130px;
  color: #ffffff;
  cursor: pointer;
  border: none;
  border-radius: 55px;
  -webkit-border-radius: 55px;
  -moz-border-radius: 55px;
  -ms-border-radius: 55px;
  -o-border-radius: 55px;
  background: rgb(16, 12, 45);
}
.backToTop:hover {
  background: rgb(21, 28, 229);
}
.wrapper {
  width: 100%;
  height: 80vh;
  margin: 36px 0;
}
.block-one {
  background: rgb(50, 19, 206);
}
.block-two {
  background: rgb(228, 146, 3);
}
.block-three {
  background: rgb(4, 147, 230);
}
.block-four {
  background: rgb(239, 53, 6);
}
.block-five {
  background: rgb(45, 35, 244);
}

Register Component in Global Component

Currently app is being served through global component; It is imperative to register the scroll to top button component to the src/App.js file.

import "./App.css";
import Profile from "./components/Profile";
function App() {
  return (
    <div>
      <Profile />
    </div>
  );
}
export default App;

Start Development Server

We have to run the development server; you can evoke the suggested command to run the react server.

npm start

On the address bar of the browser type the given url and press enter to view the app.

http://localhost:3000

How to Smooth Scroll to Top On Button Click in React

Digamber

I am Digamber, a full-stack developer and fitness aficionado. I created this site to bestow my coding experience with newbie programmers. I love to write on JavaScript, ECMAScript, React, Angular, Vue, Laravel.