How to add/edit classes on html or body tags from further down the tree using Server rendering?
Unanswered
adam.birds posted this in #help-forum
How to add/edit classes on html or body tags from further down the tree using Server rendering?
In client components I usually use this:
In client components I usually use this:
"use client"
import { useEffect } from "react";
export default function MainLayout({children}: {children: React.ReactNode}) {
useEffect(() => {
document.body.classList.add('dark:bg-gray-900');
return () => {
document.body.classList.remove('dark:bg-gray-900')
};
}, []);
return (
<>
{children}
</>
);
}2 Replies
Hi, there are different approaches, a common way to do so is to use you can use a package like
clsx and implement conditional rendering on the className prop. Here's an example:import clsx from 'clsx';
export default function RootLayout({ children }) {
return (
<html
className={clsx(
"bg-white h-full more-classes",
your_condition_if_true ? "add-this-class" : "else-add-this-class",
)}
>
{/* the rest of the code */}
</html>
)
}@adam.birds How to add/edit classes on html or body tags from further down the tree using Server rendering?
In client components I usually use this:
ts
"use client"
import { useEffect } from "react";
export default function MainLayout({children}: {children: React.ReactNode}) {
useEffect(() => {
document.body.classList.add('dark:bg-gray-900');
return () => {
document.body.classList.remove('dark:bg-gray-900')
};
}, []);
return (
<>
{children}
</>
);
}
I feel like this is an XY problem. What are you trying to do that requires you to do this? If for dark mode you can use next-themes