React - 'window is not defined' fixed with useEffect()

0 votes
90 views
added Feb 8 in React by lcjr First Warrant Officer (11,780 points)

The window object is not defined during server-side rendering, which can cause this error. To fix this, you need to ensure that the code accessing window is only executed in the client-side environment.

You can achieve this by using a conditional check to see if window is available before accessing it. Here's the updated code with this check:

useEffect(() => {
  const handleResize = () => {
    if (typeof window !== 'undefined') {
      setIsInputFocused(window.innerWidth < 768 ? true : isInputFocused);
    }
  };

  // Call handleResize initially and add event listener
  handleResize();
  if (typeof window !== 'undefined') {
    window.addEventListener('resize', handleResize);
  }

  // Remove event listener on component unmount
  return () => {
    if (typeof window !== 'undefined') {
      window.removeEventListener('resize', handleResize);
    }
  };
}, [isInputFocused]); // Dependency array includes isInputFocused

 

lazacode.org - Malaysia's programming knowledge sharing platform, where everyone can share their finding as reference to others.
...