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