d
Amit DhamuSoftware Engineer
 

Smooth Scroll to Top

2 minute read 00000 views

A simple implementation for showing a scroll top button when the user's scroll position passes a certain threshold on the Y-axis

import * as React from 'react'

const ScrollToTop = (): JSX.Element | null => {
  const [show, setShow] = React.useState(false)
  const Y_AXIS_THRESHOLD = 50

  React.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.