Answer the question
In order to leave comments, you need to log in
Is there any difference in how to check if window exists in js?
I'm starting the NextJS project. The code is first executed on the server, hence there is no window.
const [isMobile, setIsMobile] = useState(window?.innerWidth < 1000);
Answer the question
In order to leave comments, you need to log in
This is due to the fact that the html document is generated on the server. As you yourself said, there is no window object on the server, which is why it swears.
Do It
const [isMobile, setIsMobile] = useState(undefined);
const [state,setState] = useState();
useEffect(() => {
if (typeof window !== 'undefined')
setState(...)
}
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question