`document is not defined` in client component
Unanswered
Oak shoot sawfly posted this in #help-forum
Oak shoot sawflyOP
Hello. I have some code that I want to execute before React renders (changes a CSS variable). For that I'm using
This works well, the frontend is doing what I expect, but for some reason in my terminal I get
If I wrap the code in
document.documentElement.style.setPropertyThis works well, the frontend is doing what I expect, but for some reason in my terminal I get
document is not defined, despite this particularly component having the 'use client' directive.If I wrap the code in
type of window !== 'undefined', the server side error goes away, but the frontend then throws a warning in the browser consoleWarning: Extra attributes from the server: style2 Replies
@Oak shoot sawfly Hello. I have some code that I want to execute before React renders (changes a CSS variable). For that I'm using `document.documentElement.style.setProperty`
This works well, the frontend is doing what I expect, but for some reason in my terminal I get `document is not defined`, despite this particularly component having the `'use client'` directive.
If I wrap the code in `type of window !== 'undefined'`, the server side error goes away, but the frontend then throws a warning in the browser console
`Warning: Extra attributes from the server: style`
Why not use something like <html style={…}>? Client components are also server side rendered (prerendering) and you don’t have access to the window object during that step
If you want to execute it before React renders, inject a script with the
When you put some code in
When you put some code in the component, it will be pre-rendered on the server, causing the error above.
Whenever possible, use the solution suggested by joulev
<script> tag.When you put some code in
useEffect, it is only executed after hydration.When you put some code in the component, it will be pre-rendered on the server, causing the error above.
Whenever possible, use the solution suggested by joulev