Home > Software engineering >  Logging scroll position on scroll using React hooks
Logging scroll position on scroll using React hooks

Time:12-01

so I've been trying to simply get my event listener for a component to work and update on scroll. I've found this post: Get scroll position with Reactjs and I've tried the second answer (because I'm working mostly with hooks and I want my code to be consistent.) So I have this code within my component:

const [scrollPosition, setScrollPosition] = useState(0);
const handleScroll = () => {
    const position = window.scrollY;
    console.log(position);
    setScrollPosition(position);
};

useEffect(() => {
    window.addEventListener('scroll', handleScroll, { passive: true });

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

The code logs nothing to the console and whenever I try to use scroll position the value is always 0. Am I doing something wrong? Any help would be greatly appreciated!

CodePudding user response:

You are giving the dependency to the useEffect. The useEffect will only be executed once the scrollPosition is changed.

And it will never change in your code, since the useEffect is not executed. It is mutually dependent.

Try removing the scrollPosition in the useEffect dependency.

CodePudding user response:

So I finally understand why the code wasn't working. The page I was wanting to scroll was wrapped within a div. The div took up the whole page and has multiple sections. I thought that the div was simply expanding the page and that the window was still being scrolled. It turns out that I was actually scrolling within the div and not the window. So the following is what ended up working:

const scrollEvent = (e) => { 
    console.log(e.target.scrollTop)
  }
...
<div onScroll={scrollEvent}>
   ...
</div>

I'm not sure if this is the most optimal or anything but at least it gives me the scroll position I wanted. Thank you everyone who answered!

  • Related