Creating a Scroll to Top Button in ReactJS

September, 11th 2024 2 min read

A “Scroll to Top” button is a small enhancement that quickly improves user experience—especially on long pages. It gives your visitors an easy way to get back to the top without manually scrolling. In React, implementing this feature is straightforward: you track scroll position, show a button when needed, and smoothly scroll the user back to the top.

Below is a polished, easy-to-follow guide that works in any React or Next.js project.


1. Create a Top Reference

Place a reference at the top of your layout or main wrapper.

jsx
const topRef = React.useRef(null);

<div className="container" ref={topRef}>
  {/* page content */}
</div>

This ref gives us an anchor point to scroll back to.


2. Create the Scroll Handler

This function scrolls smoothly to the top when the button is clicked.

jsx
const handleScrollToTop = () => {
  window.scrollTo({
    top: topRef.current?.offsetTop ?? 0,
    behavior: "smooth",
  });
};

3. Show/Hide the Button Based on Scroll Position

We listen to the scroll event and toggle visibility.

jsx
const [showButton, setShowButton] = React.useState(false);

React.useEffect(() => {
  const toggleVisibility = () => {
    if (window.pageYOffset > 800) {
      setShowButton(true);
    } else {
      setShowButton(false);
    }
  };

  window.addEventListener("scroll", toggleVisibility);
  return () => window.removeEventListener("scroll", toggleVisibility);
}, []);

You can adjust the threshold (800px) depending on your layout.


4. Build the Scroll-to-Top Button Component

Example using a UI component (ShadCN Button is optional):

jsx
// ScrollToTopButton.tsx
import React from "react";
import { Button } from "@/components/ui/button";

const ScrollToTopButton = ({ onClick }) => {
  return (
    <Button
      className="fixed bottom-5 right-7 z-50 cursor-pointer rounded shadow-md"
      variant="secondary"
      onClick={onClick}
    >
      ↑ Top
    </Button>
  );
};

export default ScrollToTopButton;

You can replace the arrow with an SVG or an icon library like Lucide.


5. Add the Button to Your Layout

jsx
{showButton && <ScrollToTopButton onClick={handleScrollToTop} />}

The button appears only when the user scrolls down far enough.


Additional Enhancements

  • Fade-in animation using Tailwind or Framer Motion
  • A circular progress indicator showing scroll position
  • Mobile-friendly placement like bottom-center or bottom-left
  • Accessibility support (aria-label="Scroll to top")
  • Hide on small screens if not needed

These extras can make the experience feel more polished.


Conclusion

A Scroll-to-Top button is a simple but effective UI improvement. With just a few lines of React code—tracking scroll position, toggling visibility, and scrolling smoothly—you can give users a better navigation experience on long pages.

Feel free to customize the design to match your project’s style.