I have a header that I want to hide on scroll down and show on scroll up.
To do that, I saved the scrolling position as prevScrollPos
in the state to compare it to the current scrolling position onscroll
, and then update prevScrollPos
to the current:
const [visible, setVisible] = React.useState(true);
const [prevScrollPos, setPrevScrollPos] = React.useState(window.pageYOffset);
const handleScroll = () => {
const scrollPos = window.pageYOffset;
const visible = scrollPos < prevScrollPos;
setVisible(visible);
setPrevScrollPos(scrollPos);
}
The problem is that, for some reason PrevScrollPos
doesn't get updated.
Pen: https://codepen.io/moaaz_bs/pen/jgGRoj?editors=0110