Created
August 19, 2021 18:59
-
-
Save seanmodd/9f8c76e1c4d6a1d2c2a487c002bc9cfa to your computer and use it in GitHub Desktop.
ScrollToTop Component
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import { useState, useEffect } from "react"; | |
import styles from "@/styles/Scroll.module.css"; | |
import { FaArrowCircleUp } from "react-icons/fa"; | |
export default function ScrollToTop() { | |
const [isVisible, setIsVisible] = useState(false); | |
const toggleVisibilty = () => { | |
if (window.pageYOffset > 250) { | |
setIsVisible(true); | |
} else { | |
setIsVisible(false); | |
} | |
}; | |
const scrollToTop = () => { | |
window.scrollTo({ | |
top: 0, | |
behavior: "smooth", | |
}); | |
}; | |
useEffect(() => { | |
window.addEventListener("scroll", toggleVisibilty); | |
return () => { | |
window.removeEventListener("scroll", toggleVisibilty); | |
}; | |
}, []); | |
return ( | |
<div className={styles.scroll}> | |
{isVisible && ( | |
<div onClick={scrollToTop}> | |
<FaArrowCircleUp /> | |
</div> | |
)} | |
</div> | |
); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment