Next.js Discord

Discord Forum

window not defined error on server on "use client" component

Answered
aychar posted this in #help-forum
Open in Discord
          {IconComponent && (
            <IconComponent
              color={
                active &&
                window.matchMedia &&
                window.matchMedia("(prefers-color-scheme: dark)").matches
                  ? "black"
                  : ""
              }
            />
          )}


i have this component that checks for dark mode by using the window object, and at the top of the file i have "use client". however in the console on the server i see errors that window is not defined. is there a way i can make this component be "ignored" by the server?
Answered by Mandarin fish
const [isWindow, setIsWindow] = useState<boolean>(false)

useEffect(()=>{
if(window !== undefined){
setIsWindow(true)
}
},[])

Then you can now use the state to check before passing your logic, since the IsWindow would only be true when the window is defined
View full answer

6 Replies

Giant panda
Mandarin fish
NextJs is server component by default, maybe before returning the entire component itself, you would have to make sure that the window is available, or perhaps saving it in some kind of a state
Mandarin fish
const [isWindow, setIsWindow] = useState<boolean>(false)

useEffect(()=>{
if(window !== undefined){
setIsWindow(true)
}
},[])

Then you can now use the state to check before passing your logic, since the IsWindow would only be true when the window is defined
Answer
Mandarin fish
Hope you get the point?
yes that makes sense, thank you!
@aychar yes that makes sense, thank you!
Mandarin fish
You're welcome