How to use react track scroll position

August 22, 2022

In this post you will learn how to use React.js to keep track of scroll position on a web page.

TLDR at the bottom


The react code below tracks the scroll position for a functional component.

  Some code...
import React, { useLayoutEffect, useState } from 'react'

function ScrollTopTop() {
    // track state of scroll bar in webpage
    const [state, setState] = useState(0);
    useLayoutEffect(() => {
        // event listener to track
        const handleScroll = () => {
            const position = window.pageYOffset;
            setState(position);
        }
        // add the event listener
        window.addEventListener('scroll', handleScroll);
        // return function
        return () => {
            window.removeEventListener("scroll", handleScroll);
        }
    }, [])

We assign a function to handle the scroll event. The attribute on window "pageYOffSet" tells us where we are on a page.


Next we add the event to the webpage by using window.addEventListener. The return function makes sure that react won't add many copies of the handleScroll event. React will remove the window event listener each time this button is removed from the page.


Below is an easy way to only show the button if a user has scrolled down a little on the webpage. "state" just represents how far down the page a user is. 0 represents any amount a user has scrolled down a page. A more realistic number might be around 200.


Finally window.scrollTo(0,0) tells the browser to scroll to the top of the page.

  Some code...

    return (

        <>

     { state > 0 &&
          <button className="rounded" onClick={() => {window.scrollTo(0,0)}}>
            To Top
          </button>
     }
        </>

    )

}

export default ScrollTopTop


Test it out:



Full code

  Some code...
import React, {useLayoutEffect, useState} from 'react'

function ScrollTopTop() {

    const [state, setState] = useState(0);

    useLayoutEffect(() => {

        const handleScroll = () => {
            const position = window.pageYOffset;
            setState(position);
        }

        window.addEventListener('scroll', handleScroll);

        return () => {
            window.removeEventListener("scroll", handleScroll);
        }
    },[])

    return (

        <>
     { state > 0 &&
          <button className="rounded dark:bg-indigo-400 bg-indigo-600 text-black dark:text-white" onClick={() => {window.scrollTo(0,0)}}>
            To Top
          </button>
     }
        </>
    )
}
export default ScrollTopTop