d
Amit DhamuSoftware Engineer
 

Scroll Progress Bar Indicator

1 minute read 00000 views

To create a progress indicator bar which updates as you scroll like the one on this page underneath the header bar, you can implement something like this:

const ProgressBar = (): JSX.Element => {
  const [scrolled, setScrolled] = React.useState('')

  React.useEffect(() => {
    window.addEventListener('scroll', onScroll)

    return () => window.removeEventListener('scroll', onScroll)
  }, [])

  const onScroll = () => {
    const viewportHeight =
      document.documentElement.scrollHeight - window.innerHeight

    setScrolled(
      `${(document.documentElement.scrollTop / viewportHeight) * 100}%`
    )
  }

  return (
    <div style={{ position: 'fixed', top: '0' }}>
      <div style={{ width: scrolled, backgroundColor: 'blue', height: '2px' }}>
        &nbsp;
      </div>
    </div>
  )
}