sorry about the messy code. Really getting myself in a tangle here.
I have a Nav
component that I want to hide when the user scrolls. The scroll is detected using the event listener (which is now in useEffect
, I don't really know why) which calls scrollDetect()
.
scrollDetect
then sets a state variable, scrollState
which is hooked up to the CSS via styled components.
It all works very well, except that I want to stop the event listener when the nav "tray" is open. The open state of the nav tray is stored in isOpen[1]
, but it's just not being updated in the right order. Whenever the nav tray is open, the buttons are still hiding on scroll. To see the behavior I'm referring to, check out erasebegin.net. Try clicking one of the menu buttons and then scrolling the window.
I have pored over all kinds of guides, posts and documentation, but am going in so many circles and going a little crazy over this, please help.
export default function Nav() {
const [isOpen, setIsOpen] = useState(["", false]);
const [envOpen, setEnvOpen] = useState(false);
const [scrollState, setScrollState] = useState("show");
// HIDE NAVBUTTONS ON DOWN SCROLL, REVEAL ON UP SCROLL
var lastScrollTop = window.pageYOffset || window.scrollTop;
const scrollDetect = () => {
if (isOpen[1] === false) {
var st = window.pageYOffset || document.documentElement.scrollTop;
if (st < lastScrollTop) {
setScrollState("show");
} else if (st > lastScrollTop) {
setScrollState("hide");
}
lastScrollTop = st <= 0 ? 0 : st;
}
};
useEffect(() => {
console.log(isOpen[1]);
const listener = document.addEventListener("scroll", scrollDetect);
const cleanup = () => {
document.removeEventListener("scroll", listener);
return cleanup;
};
}, [isOpen[1]]);
const setOpen = ([title, state]) => {
let newState = !state;
setIsOpen([title, newState]);
};
const envelopeOpen = () => {
setEnvOpen(true);
};
const envelopeClose = () => {
setEnvOpen(false);
};