Home > database >  Event listner not listening to scroll event in Next JS
Event listner not listening to scroll event in Next JS

Time:11-15

I'm trying to update the state and show shadow in nav if user scrolls but it's not listening to the event.
i'm using nextJS 13 and tailwind css.

const [shadow, setShadow] = useState(false);

useEffect(() => {
  const handleShadow = () => {
    if (window.scrollY >= 90) {
      setShadow(true);
    } else {
      setShadow(false);
    }
    window.addEventListener("scroll", handleShadow, true);
  };
  return window.removeEventListener("scroll", handleShadow);
}, []);

in my div

<div
  className={
    shadow
      ? "fixed left-0 top-0 w-full z-10 ease-in duration-300 bg-[#112240] shadow-xl"
      : "fixed left-0 top-0 w-full z-10 ease-in duration-300 bg-[#112240]"
  }
>
other code
</div>

CodePudding user response:

The problem in your code comes from the fact that you are initializing the event listener inside your handleShadow function, so simply moving it out of the function's body should do the trick.

const [shadow, setShadow] = useState(false);

useEffect(() => {
  const handleShadow = () => {
    if (window.scrollY >= 90) {
      setShadow(true);
    } else {
      setShadow(false);
    }
  };
  window.addEventListener("scroll", handleShadow, true); //moved it out the function's body
  return window.removeEventListener("scroll", handleShadow);
}, []);

CodePudding user response:

Try this

useEffect(() => {
const handleShadow = () => {
  if (window.scrollY >= 90) {
    setShadow(true);
  } else {
    setShadow(false);
  }
};
window.addEventListener("scroll", handleShadow);
 }, []);
  • Related