Next.js Discord

Discord Forum

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
Open in Discord
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:

"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>
  )
}