Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

WebpackError: ReferenceError: window is not defined #22

Open
Betanya opened this issue Jul 31, 2020 · 3 comments
Open

WebpackError: ReferenceError: window is not defined #22

Betanya opened this issue Jul 31, 2020 · 3 comments

Comments

@Betanya
Copy link
Collaborator

Betanya commented Jul 31, 2020

We are trying to make the embedded video responsive, but this is the error that is happening when we try to deploy: "window" is not available during server side rendering.

Here is the relevant code:

const VideoWelcome: React.FunctionComponent = () => {
const scale = 0.5;
const minWidth = 800;
const [width, setWidth] = useState(calculateWidth(window.innerWidth));
const height = (9 / 16) * width;

useEffect(() => {
window.addEventListener('resize', handleResize);
return () => window.removeEventListener('resize', handleResize);
}, []);

function calculateWidth(width: number): number {
if (width < minWidth) return width;
return width * scale;
}

function handleResize(e: any) {
const height = e.target.innerHeight;
const width = e.target.innerWidth;
setWidth(calculateWidth(width));
console.log(height, width);
}

@clayrisser
Copy link
Collaborator

Can you put the full error here?

@Betanya
Copy link
Collaborator Author

Betanya commented Aug 3, 2020

image

@clayrisser
Copy link
Collaborator

@Betanya that is happening because it is running that function during the build, which won't work because the build happens outside of a browser. The window object is only available in a browser. You can work around this by first checking if window is undefined before using it in the useState function.

For example . . .

const [width, setWidth] = useState(calculateWidth(typeof window === 'undefined' ? 0 : window.innerWidth));

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

2 participants