https://github.com/being-devahmad/scrolltotop
just code for scroll to top
https://github.com/being-devahmad/scrolltotop
Last synced: 3 months ago
JSON representation
just code for scroll to top
- Host: GitHub
- URL: https://github.com/being-devahmad/scrolltotop
- Owner: being-devahmad
- Created: 2024-09-14T11:21:51.000Z (over 1 year ago)
- Default Branch: main
- Last Pushed: 2024-09-14T11:24:13.000Z (over 1 year ago)
- Last Synced: 2025-02-07T01:31:55.053Z (over 1 year ago)
- Size: 4.88 KB
- Stars: 1
- Watchers: 1
- Forks: 0
- Open Issues: 0
-
Metadata Files:
- Readme: README.md
Awesome Lists containing this project
README
# ScrollToTop Component
This is a React component that adds a "Scroll to Top" button to your web page. The button appears when the user scrolls down the page and allows them to quickly return to the top of the page with a smooth scrolling animation.
## Features
- Appears after scrolling down 300 pixels
- Smooth scrolling animation
- Responsive design
- Customizable styling
## Usage
To use this component in your React project, simply import it and add it to your main layout or any page where you want the scroll-to-top functionality.
```jsx
import { 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 > 300) {
setIsVisible(true);
} else {
setIsVisible(false);
}
};
window.addEventListener("scroll", toggleVisibility);
return () => window.removeEventListener("scroll", toggleVisibility);
}, []);
return (
{isVisible && (
)}
);
}