Anjanesh Lekshminarayanan
Anjanesh

Anjanesh

Adding classes to the body of a NextJS application

Anjanesh Lekshminarayanan's photo
Anjanesh Lekshminarayanan
·Jan 26, 2022·

1 min read

Subscribe to my newsletter and never miss my upcoming articles

If you want to add a class (className) to the body tag of a a NextJS page, you'll need to add it via JavaScript in the useEffect (or componentDidMount if you're using class-based components) Lifecycle function.

This adds TailWindCSS's font-light and text-gray-700 classes to the body tag.

import { useEffect } from 'react';
import type { NextPage } from 'next';

import Nav from './Nav';
import Header from './Header';
import Footer from './Footer';

const Layout: NextPage = ({children}) =>
{
    useEffect(() =>
    {        
        document.body.classList.add("font-light");
        document.body.classList.add("text-gray-700");
    });

    return (
        <>
        <div>       
            <Header />
            <header className="bg-white"> 
                <Nav />
            </header>
            <div>                
                {children}
            </div>            
        </div>        
        <Footer />
        </>
        );
}

export default Layout
 
Share this