A simple implementation for showing a scroll top button when the user's scroll position passes a certain threshold on the Y-axis
import { useState, useEffect } from 'react'
const ScrollToTop = () => {
const [show, setShow] = useState(false)
const Y_AXIS_THRESHOLD = 50
useEffect(() => {
window.addEventListener('scroll', onScroll)
return () => window.removeEventListener('scroll', onScroll)
}, [])
const onScroll = () => {
setShow(window.scrollY > Y_AXIS_THRESHOLD)
}
if (!show) {
return null
}
return (
<button
onClick={() => {
window.scrollTo({
top: 0,
behavior: 'smooth',
})
}}
>
Scroll to top
</button>
)
}
export default ScrollToTop
For devices that don't support the scroll-behaviour API, you can use a polyfill such as this one.