React Component to Smooth Scroll to the Top
Pranav Birajdar
March 17, 2021
442 💖
It's kinda rare to find a smooth scrolling button that takes you to the top of the page on modern blogging websites, especially the ones that are a long 15 minute read!
However, whenever I come across one, I always tend to use it and appreciate the elegance of this simple button that has such a specific job.
After perusing Stack Overflow and GitHub for solution, I came across an elegant React component that uses Hooks and wanted to share it with this community!
Our button should function like this:
These are following test-cases for our component:
- Button should always be at the right bottom of the page
- Button should be hidden and should only appear when we scroll for a certain height
- On clicking it, we should be smoothly taken to the top of the page
The Hook component achieves the following functionality.
import React, { useEffect, useState } from "react";
export default function ScrollToTop() {
const [isVisible, setIsVisible] = useState(false);
// Top: 0 takes us all the way back to the top of the page
// Behavior: smooth keeps it smooth!
const scrollToTop = () => {
window.scrollTo({
top: 0,
behavior: "smooth"
});
};
useEffect(() => {
// Button is displayed after scrolling for 500 pixels
const toggleVisibility = () => {
if (window.pageYOffset > 500) {
setIsVisible(true);
} else {
setIsVisible(false);
}
};
window.addEventListener("scroll", toggleVisibility);
return () => window.removeEventListener("scroll", toggleVisibility);
}, []);
//scroll-to-top classes: fixed, bottom:0, right:0
return (
<div className="scroll-to-top">
{isVisible && (
<div onClick={scrollToTop}>
<h3>Go up!</h3>
</div>
)}
</div>
);
}
We're almost done! Just import this component in your react file and stick it at the very end.
And voila, it should work!
Here is a basic, quick, and ugly demo of how it should function!