Created
February 6, 2025 01:39
-
-
Save jasonrundell/83efa4f801f4bd2a0ab4a20510b7c55a to your computer and use it in GitHub Desktop.
This file contains hidden or 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 { styled } from '@pigment-css/react' | |
const BackToTopStyle = styled('div')<BackToTopStyleProps>({ | |
position: 'fixed', | |
bottom: `${Tokens.sizes.xlarge}rem`, | |
right: `${Tokens.sizes.xlarge}rem`, | |
backgroundColor: '#e9be62', | |
color: '#000', | |
padding: `${10 / 16}rem ${Tokens.sizes.medium}rem`, | |
borderRadius: `${5 / 16}rem`, | |
cursor: 'pointer', | |
'&:hover': { | |
backgroundColor: Tokens.colors.secondary, | |
}, | |
variants: [ | |
{ | |
props: { | |
isVisible: true, | |
}, | |
style: { | |
display: 'block', | |
}, | |
}, | |
{ | |
props: { | |
isVisible: false, | |
}, | |
style: { | |
display: 'none', | |
}, | |
}, | |
], | |
}) | |
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