Skip to main content

Adding classes to the body of a NextJS application

Published 1 min readMarkdown

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

About the author

  • I am a web developer from Navi Mumbai. Mainly dealt with LAMP stack, now into Django and getting into Laravel and Cloud. Founder of nerul.in and gaali.in

No comments yet. Be the first to comment.