1

I'm using React and I need to get a scroll direction in order to do some stuff. I have a working code but I'm clueless on how to store and update previous scroll position.

Here's my code:

componentDidMount(){
    const prev = window.scrollY;
    window.addEventListener('scroll', e => this.handleNavigation(e, prev);
}

Visible problem here is that componentDidMount fires only once so when I try to do the following:

handleNavigation = (e, prev) =>{
    const window = e.currentTarget;

    if(prev > window.scrollY){
        console.log("scrolling up");
    }
    else if(prev < window.scrollY){
        console.log("scrolling down");
    }
};

It compares values properly but prev never changes, so it doesn't work as intended. How do I make it work?

Do I put prev inside the interval to update the value or something crazy like that?

halfer
  • 19,824
  • 17
  • 99
  • 186
devBem
  • 820
  • 4
  • 11
  • 17

1 Answers1

11

Try the following. It should work since this way the previous value is stored in the instance of the component.

componentDidMount() {
    this.prev = window.scrollY;
    window.addEventListener('scroll', e => this.handleNavigation(e));
}

handleNavigation = (e) => {
    const window = e.currentTarget;

    if (this.prev > window.scrollY) {
        console.log("scrolling up");
    } else if (this.prev < window.scrollY) {
        console.log("scrolling down");
    }
    this.prev = window.scrollY;
};
mvidalgarcia
  • 538
  • 1
  • 5
  • 14
pinturic
  • 2,253
  • 1
  • 17
  • 34
  • Yep, that's working and obvious solution. Thank you for unstucking my brain. – devBem May 18 '18 at 13:24
  • For those who are looking for more precise implementation in react hooks, it can be found in this [post](https://stackoverflow.com/questions/62497110/detect-scroll-direction-in-react-js/62497293#62497293). – SMAKSS Jun 21 '20 at 15:36
  • You can find an answer without any state management here: https://stackoverflow.com/a/65534697/7207514 – Deiv Jan 02 '21 at 16:12