Adding classes to the body of a NextJS application
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