44 lines
893 B
JavaScript
44 lines
893 B
JavaScript
"use client";
|
|
|
|
import { useState, useEffect } from 'react';
|
|
import styles from './ScrollToTop.module.css';
|
|
|
|
export default function ScrollToTop() {
|
|
const [isVisible, setIsVisible] = useState(false);
|
|
|
|
// Show button when page is scrolled down
|
|
const toggleVisibility = () => {
|
|
if (window.scrollY > 300) {
|
|
setIsVisible(true);
|
|
} else {
|
|
setIsVisible(false);
|
|
}
|
|
};
|
|
|
|
const scrollToTop = () => {
|
|
window.scrollTo({
|
|
top: 0,
|
|
behavior: 'smooth',
|
|
});
|
|
};
|
|
|
|
useEffect(() => {
|
|
window.addEventListener('scroll', toggleVisibility);
|
|
return () => window.removeEventListener('scroll', toggleVisibility);
|
|
}, []);
|
|
|
|
return (
|
|
<>
|
|
{isVisible && (
|
|
<button
|
|
onClick={scrollToTop}
|
|
className={styles.scrollToTopBtn}
|
|
aria-label="Scroll to top"
|
|
>
|
|
↑
|
|
</button>
|
|
)}
|
|
</>
|
|
);
|
|
}
|