In my NextJS app I can't seem to access window
Unhandled Rejection (ReferenceError): window is not defined
componentWillMount() {
console.log('window.innerHeight', window.innerHeight);
}
In my NextJS app I can't seem to access window
Unhandled Rejection (ReferenceError): window is not defined
componentWillMount() {
console.log('window.innerHeight', window.innerHeight);
}
With No SSR
https://github.com/zeit/next.js#with-no-ssr
componentWillMount()
lifecycle hook works both on server as well as client side. In your case server would not know aboutwindow
ordocument
during page serving, the suggestion is to move the code to eitherSolution 1:
Or, Solution 2
In case it is something that you only want to perform in then you could write something like:
If you use React Hooks you can move the code into the Effect Hook:
The code inside
useEffect
is only executed on the client (in the browser), thus it has access towindow
.In the constructor of your Class Component you can add
Example:
import React, { Component } from 'react'
class MyClassName extends Component {
}
This will avoid the error (in my case the error would occur after I would click reload of the page)
Other solution is by using
process.browser
to just execute your command during rendering in client side only.Move the code from
componentWillMount()
tocomponentDidMount()
:In NextJS,
componentDidMount()
is executed only the client wherewindow
and other browser specific APIs will be available. From the NextJS wiki:Along the same lines,
componentWillMount()
will be deprecated in v17 of React so it effectively will be potentially unsafe to use in the very near future.