Skip to content

Instantly share code, notes, and snippets.

@iaurg
Created July 14, 2021 22:25
Show Gist options
  • Save iaurg/4dc7d1612717d2e7ecfbe52de3382e0c to your computer and use it in GitHub Desktop.
Save iaurg/4dc7d1612717d2e7ecfbe52de3382e0c to your computer and use it in GitHub Desktop.
scroll to top next.js
const BackTotop = () => {
const [showScroll, setShowScroll] = useState(false)
const checkScrollTop = () => {
if (!showScroll && window.pageYOffset > 400) {
setShowScroll(true)
} else if (showScroll && window.pageYOffset <= 400) {
setShowScroll(false)
}
}
const scrollTop = () => {
window.scrollTo({ top: 0, behavior: 'smooth' })
}
if (typeof window !== 'undefined') {
window.addEventListener('scroll', checkScrollTop)
}
return (
<BackButton
data-testid="back-to-top"
aria-label="Voltar ao topo"
onClick={scrollTop}
style={{ height: 40, display: showScroll ? 'flex' : 'none' }}
/>
)
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment