window not defined error on server on "use client" component
Answered
aychar posted this in #help-forum
aycharOP
{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 North Pacific hake
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
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
6 Replies
Asian black bear
North Pacific hake
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
North Pacific hake
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
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
North Pacific hake
Hope you get the point?
aycharOP
yes that makes sense, thank you!
@aychar yes that makes sense, thank you!
North Pacific hake
You're welcome