Last active
May 2, 2021 04:00
-
-
Save JayMGurav/2c24d35e1ea5893f7d7bd78d7fb4707b to your computer and use it in GitHub Desktop.
A custom scroll-to-top hook
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 { useEffect, useState } from "react"; | |
export default function scrollToTop(){ | |
const [isBtnVisible, setIsBtnVisible] = useState(false); | |
const [pageYOffset, setPageYOffset] = useState(0); | |
useEffect(()=>{ | |
const checkVisiblity = () => { | |
setPageYOffset(window.pageYOffset); | |
if(pageYOffset > window.innerHeight){ | |
setIsBtnVisible(true); | |
}else{ | |
setIsBtnVisible(false); | |
} | |
} | |
window.addEventListener('scroll', checkVisiblity); | |
return () => window.removeEventListener('scroll', checkVisiblity); | |
},[pageYOffset]); | |
const scrollToTop = () => { | |
if(window && isVisible){ | |
window.scrollTo({ | |
top: 0, | |
behavior:"smooth" | |
}); | |
} | |
} | |
return [isBtnVisible, scrollToTop]; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment