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?