Categories
React Answers

How to Add a Smooth Scrolling Back To Top Button with React?

Spread the love

Sometimes, we want how to add a smooth scrolling back to top button with React.

In this article, we’ll look at how to add a smooth scrolling back to top button with React.

Add a Smooth Scrolling Back To Top Button with React

To add a smooth scrolling back to top button with React, we can create our own function to scroll up the screen until we reach the top.

Then we can use that function as the click handler for the scroll to top button.

For instance, we write:

import React from "react";

export default function App() {
  const scrollUp = () => {
    const doc = document.documentElement;
    const top = (window.pageYOffset || doc.scrollTop) - (doc.clientTop || 0);

    if (top > 0) {
      window.scrollTo(0, top - 15);
      setTimeout(scrollUp, 10);
    }
  };

  return (
    <div>
      {Array(200)
        .fill()
        .map((_, i) => (
          <p key={i}>{i}</p>
        ))}
      <button onClick={scrollUp}>scroll to top</button>
    </div>
  );
}

We have the scrollUp function that takes the document.documentElement element which is the element with the whole page’s contents.

Then we get the top position to scroll to with (window.pageYOffset || doc.scrollTop) - (doc.clientTop || 0).

And if top is bigger than 0, we call window.scrollTo to scroll higher up the page.

Then we call scrollUp after a timeout to keep scrolling until we reached the top.

Finally, we set scrollUp as the value of onClick so that we get smooth scrolling back to the top of the page when we click on the scroll to top button.

Conclusion

To add a smooth scrolling back to top button with React, we can create our own function to scroll up the screen until we reach the top.

Then we can use that function as the click handler for the scroll to top button.

By John Au-Yeung

Web developer specializing in React, Vue, and front end development.

Leave a Reply

Your email address will not be published. Required fields are marked *