Home > database >  Window is not defined errors in React and Next.js
Window is not defined errors in React and Next.js

Time:10-18

I'm using React Hooks and NextJS. I'm about to create a Navbar along with its functionality. But, by the time I'm going to refresh my page, this error is shown up.

Back when I was using this code on my React Project, it worked perfectly fine.

Can somebody help me where did it go wrong?enter image description here

I also attach my full code here: enter image description here

CodePudding user response:

As Shivam mentioned in comment, you cannot use window object in server. you can do following

useEffect(() => {
    if (typeof window !== "undefined") {
      window.addEventListener("resize", showButton)
    }
    return () => window.removeEventListener("resize", showButton)
  }, [showButton)

CodePudding user response:

Try this

window.addEventListener('resize', function() { console.log('addEventListener - resize'); }, true);

  • Related