Next.js Discord

Discord Forum

(App dir) Setting classnames on <body> from a page?

Unanswered
Tan posted this in #help-forum
Open in Discord
TanOP
I want to add a class (a tailwind theme) to <body> depending on a fetch call that on each page. How can I do this in app dir?

Pages had the handy <Head>-component, but that looks to be obsolete 🤷‍♂️

5 Replies

if this is a side effect you could just do
document.body.classList.add('classname')
TanOP
Do you mean in a useEffect? If I do that then the initial preloaded html will not have the class, it will be added when js is added, which will produce a flicker in the ui 🤷‍♂️
@Tan Do you mean in a useEffect? If I do that then the initial preloaded html will not have the class, it will be added when js is added, which will produce a flicker in the ui 🤷‍♂️
this only works in useEffect or in an event handler. when you say fetch call do you mean an awaited call in a React Server Component? if so then I think it could only work if you do this call in app/layout.tsx
TanOP
Right, sorry I wasn't very clear: Yes, each page has a RSC that fetches data from a CMS, among that data is theme which I need to place as a class on the body.

app/layout.tsx don't work cause it's not updating on page transitions, right?
Löwchen
I would love to the same thing..