Skip to content

Instantly share code, notes, and snippets.

@jasonrundell
Created February 6, 2025 01:53
Show Gist options
  • Save jasonrundell/445b09b8afc1739c8c617b89f8eb0f3b to your computer and use it in GitHub Desktop.
Save jasonrundell/445b09b8afc1739c8c617b89f8eb0f3b to your computer and use it in GitHub Desktop.
import styled from '@emotion/styled'
const BackToTopStyle = styled.div`
position: fixed;
bottom: ${tokens['--size-xlarge']};
right: ${tokens['--size-xlarge']};
background-color: #e9be62;
color: #000;
padding: 0.625rem 1.25rem;
border-radius: 0.3125rem;
cursor: pointer;
display: ${isVisible ? 'block' : 'none'};
&:hover {
background-color: #eee;
}
`
const BackToTop: React.FC = () => {
const [isVisible, setIsVisible] = useState(false)
const toggleVisibility = () => {
if (window.pageYOffset > 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 (
<BackToTopStyle
onClick={scrollToTop}
onKeyPress={(e) => {
if (e.key === 'Enter' || e.key === ' ') {
scrollToTop()
}
}}
role="button"
tabIndex={0}
aria-label="Back to top"
isVisible={isVisible}
>
Back to top
</BackToTopStyle>
)
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment