DEV Community

Discussion on: Window not defined

Collapse
 
sfiquet profile image
Sylvie Fiquet

I don't get what your point is, are you asking for help?

It's normal to get an error, window is not defined on the server. Remember that Next runs your code on the server when building the HTML file.

Initialise your state to 0 and update it to window.innerWidth in useEffect.

Collapse
 
jishnu02 profile image
Jishnu-02

can u show me how to do it?

Collapse
 
sfiquet profile image
Sylvie Fiquet

Something like that:

const [windowWidth, setWindowWidth] = useState(0)

// runs only once, on mount
useEffect(() => {
  if (window !== undefined){
    setWindowWidth(window.innerWidth)
    window.addEventListener('resize', handleWindowWidth)
  }
}, [])
Enter fullscreen mode Exit fullscreen mode
Thread Thread
 
jishnu02 profile image
Jishnu-02

Thank You.