In my Next.js app I can't seem to access window:
Unhandled Rejection (ReferenceError): window is not defined
componentWillMount() {
console.log('window.innerHeight', window.innerHeight);
}
Another solution is to use p̶r̶o̶c̶e̶s̶s̶.̶b̶r̶o̶w̶s̶e̶r to bit Execute ̶ your command during rendering on the client side only.
But the process object has been deprecated in Webpack5 and also in NextJS, because it is a NodeJS variable for the back-end side only.
So we have to use the browser window object
if (typeof window != "undefined") { // Client-side-only code } Another solution is to use the react hook to override the componentDidMount
useEffect(() => { // Client-side-only code })Move the code from componentWillMount() to componentDidMount() :
componentDidMount() { console.log('window.innerHeight', window.innerHeight); } In Next.js, componentDidMount() is executed only on the client where the window and other browser-specific APIs will be available. From the Next.js wiki :
Next.js is universal, which means it executes code first on the server side and then on the client side. The window object is only present on the client side, so if you absolutely need to access it in some React component, you should put that code in componentDidMount. This lifecycle method will only run on the client. You may also want to check if there isn't some alternative universal library that might meet your needs.
Along the same lines, componentWillMount() will be deprecated in React version 17, making it potentially unsafe to use in the very near future.
Yes
If you use React Hooks you can move the code into the Effect Hook:
import * as React from "react";
export const MyComp = () => {
React.useEffect(() => {
// window is accessible here.
console.log("window.innerHeight", window.innerHeight);
}, []);
return (<div></div>)
}
The code inside useEffect is only executed on the client (in the browser), thus it has access to window.