Skip to content

Instantly share code, notes, and snippets.

@droganov
Last active June 2, 2023 14:53
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save droganov/43effd339d5307b38059aea427fa6ebc to your computer and use it in GitHub Desktop.
Save droganov/43effd339d5307b38059aea427fa6ebc to your computer and use it in GitHub Desktop.
Conditional body class in Next.js 13 using app segments
'use client'
import { FunctionComponent } from 'react'
import { useSelectedLayoutSegments } from 'next/navigation'
import clsx from 'clsx'
import '../styles/globals.css'
type Props = {
children: JSX.Element
}
const RootLayout: FunctionComponent<Props> = ({ children }) => {
const [segment] = useSelectedLayoutSegments()
const isPrimary = segment === '(primary)'
return (
<html lang="en">
<body className={clsx(isPrimary && 'yobta-primary')}>
{children}
</body>
</html>
)
}
export default RootLayout
@droganov
Copy link
Author

droganov commented Jun 2, 2023

This gist provides a straightforward method for setting a body class name in Next.js 13, eliminating the need for third-party libraries.

It's designed for /src/page.tsx. By adding a (primary) route group in your /src/app directory, it allows you to easily append a class to all pages within that group.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment