5

I am getting error while building the app for the production. And it kept saying that ReferenceError: window is not defined. I am lost to solve the problem

FullCode:

const [windowSize, setWindowSize] = useState<WindowInfo>({
        width: window.innerWidth,
        height: window.innerHeight,
    });

    useEffect(() => {
        if (typeof window !== "undefined") { // error showing in this line
            function handleResize() {
                const data: WindowInfo = {
                    width: window.innerWidth,
                    height: window.innerHeight,
                }

                setWindowSize(data);
            }

            window.addEventListener("resize", handleResize);

            handleResize();

            return () => window.removeEventListener("resize", handleResize);
        }
    }, []);

anyone can tell me the workaround of this problem

1 Answer 1

4

window is a browser only thing. On the NodeJS server, window will not be defined.

You are already handling this inside of useEffect, but not in useState. You need something like this:

const isBrowser = (typeof window !== "undefined");
const [windowSize, setWindowSize] = useState<WindowInfo>({
    width: isBrowser ? window.innerWidth : 0,
    height: isBrowser ? window.innerHeight : 0,
});

I used 0 as a default in the above, but you can use whatever is sensible for your project.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.