Lesson 41 of 52Tailwind in practice
Tailwind with React and Next.js
Use Tailwind in a real Next.js App Router project: setup, className, variants with cva, cn(), class-based dark mode, next/font and shadcn/ui.
So far you have written Tailwind classes into plain HTML. Most Tailwind code at work lives somewhere else: inside React components, usually in a Next.js app. The classes are the same, but a few new questions appear. Where does the CSS file go? How does a Button turn a variant prop into classes? How do you add a dark mode toggle, a custom font, or a ready-made dialog? This lesson answers each of those with the patterns you will see in real codebases, so that opening a professional Next.js project feels familiar instead of overwhelming.
Tailwind in a Next.js App Router project
Next.js is a React framework. Its App Router is the app/ folder, where each folder is a URL and a layout.tsx file wraps every page beneath it. When you run npx create-next-app@latest, the setup wizard asks whether you want Tailwind, and if you say yes it does everything below for you. It is still worth knowing the pieces, because sooner or later you will add Tailwind to an existing app or debug one where it stopped working.
Next.js processes CSS through PostCSS, a tool that runs plugins over your stylesheets. Tailwind version 4 ships a PostCSS plugin, so a manual setup is three small steps:
npm install tailwindcss @tailwindcss/postcss postcssconst config = {
plugins: {
"@tailwindcss/postcss": {},
},
};
export default config;/* app/globals.css */
@import "tailwindcss";// app/layout.tsx
import "./globals.css";
export default function RootLayout({ children }: { children: React.ReactNode }) {
return (
<html lang="en">
<body className="bg-white text-slate-900 antialiased">{children}</body>
</html>
);
}The root layout imports globals.css once, and because every page renders inside that layout, every page gets Tailwind. There is no tailwind.config.js in a fresh version 4 project: your tokens go in globals.css under @theme, exactly as in the design systems lesson.
- my-app/
- postcss.config.mjsloads @tailwindcss/postcss
- package.json
- app/
- globals.css@import "tailwindcss"; plus @theme
- layout.tsximports globals.css, sets fonts
- page.tsxthe home page
- components/
- ui/
- button.tsxshared UI pieces
- lib/
- utils.tsthe cn() helper
Put the manual Tailwind setup for a Next.js app in order.
- Tap the steps below in the right order.
className, and why Tailwind suits server components
In JSX you write className instead of class, because class is a reserved word in JavaScript. Everything else is identical: className="flex items-center gap-2".
Tailwind produces a plain CSS file at build time. Nothing runs in the browser to apply styles. That matters in the App Router, where components are React Server Components by default: they render on the server and send no JavaScript for themselves. A server component can use any Tailwind class, because a class is just a string in the HTML. You only add "use client" when a component needs state, effects or event handlers, never because of styling.
Props to classes: a variants map, then cva
A component usually needs a few looks: a primary and a secondary button, a small and a large size. You saw the simplest version in the design systems lesson, an object that maps each variant name to a full class string. As the options grow (variant times size times state), teams reach for class-variance-authority, usually shortened to cva. It is a small library that turns that map into a typed function.
const VARIANTS = {
primary: "bg-indigo-600 text-white hover:bg-indigo-500",
ghost: "text-slate-700 hover:bg-slate-100",
} as const;
type Props = React.ComponentProps<"button"> & {
variant?: keyof typeof VARIANTS;
};
export function Button({ variant = "primary", className, ...props }: Props) {
return (
<button
className={cn("rounded-lg px-4 py-2 font-medium", VARIANTS[variant], className)}
{...props}
/>
);
}import { cva, type VariantProps } from "class-variance-authority";
import { cn } from "@/lib/utils";
const button = cva(
"inline-flex items-center gap-2 rounded-lg font-medium focus-visible:outline-2 focus-visible:outline-offset-2 disabled:opacity-50",
{
variants: {
variant: {
primary: "bg-indigo-600 text-white hover:bg-indigo-500",
ghost: "text-slate-700 hover:bg-slate-100",
},
size: {
sm: "px-3 py-1.5 text-sm",
md: "px-4 py-2",
},
},
defaultVariants: { variant: "primary", size: "md" },
},
);
type Props = React.ComponentProps<"button"> & VariantProps<typeof button>;
export function Button({ variant, size, className, ...props }: Props) {
return <button className={cn(button({ variant, size }), className)} {...props} />;
}The cva version gives you three things for free: the base classes in one place, a defaultVariants fallback, and TypeScript types. VariantProps<typeof button> means <Button variant="danger"> is a type error until someone adds a danger variant. cva also supports compoundVariants for classes that apply only to a combination, such as "ghost and small".
Both versions end with cn(..., className). As a reminder from the design systems lesson, cn is a three-line helper usually kept in lib/utils.ts:
import { clsx, type ClassValue } from "clsx";
import { twMerge } from "tailwind-merge";
export function cn(...inputs: ClassValue[]) {
return twMerge(clsx(inputs));
}clsx drops falsy values so you can write isActive && "bg-slate-900", and twMerge removes conflicts so a caller's className="px-8" really replaces the component's px-4. Accepting className and merging it last is the convention almost every React component library follows.
Here is what that Button renders to in the browser, with each variant and size:
Preview
The browser never sees variant or size. By the time the HTML arrives, cva has already chosen the strings. Try swapping the indigo for emerald on the first button: that is the edit a success variant would make.
Never build class names from pieces
This is the bug every React developer hits once. Tailwind finds classes by scanning your source files as plain text at build time. It never runs your code. So this cannot work:
// Broken: the text "bg-red-500" never appears in any file
<span className={`bg-${color}-500`}>{label}</span>Tailwind sees bg-${color}-500, which is not a class, and generates nothing. The badge renders with no background, but only for colours you have not happened to use elsewhere, which makes the bug confusing. The fix is to keep every class written out in full and choose between them:
const TONES = {
success: "bg-emerald-100 text-emerald-800",
warning: "bg-amber-100 text-amber-800",
danger: "bg-red-100 text-red-800",
} as const;
<span className={TONES[tone]}>{label}</span>For truly data-driven values, such as a progress bar at 37 percent or a chart bar for a number from an API, no class could ever cover every value. Pass the number as a CSS variable in style and let a class read it:
<div className="h-2 w-(--progress) rounded-full bg-indigo-600" style={{ "--progress": `${pct}%` } as React.CSSProperties} />text- followed by the size prop, which is lg. The text is not large in production. Why?Dark mode with a class and a toggle
By default, dark: follows the operating system through prefers-color-scheme. Most apps want a toggle so people can choose. You switch the dark variant to a class strategy with one line in globals.css:
@import "tailwindcss";
@custom-variant dark (&:where(.dark, .dark *));Now dark:bg-slate-900 applies when the element or any ancestor has the class dark. A toggle is a small client component that adds or removes that class on <html> and remembers the choice:
"use client";
export function ThemeToggle() {
function toggle() {
const isDark = document.documentElement.classList.toggle("dark");
localStorage.setItem("theme", isDark ? "dark" : "light");
}
return (
<button onClick={toggle} className="rounded-lg border px-3 py-1.5 text-sm dark:border-slate-700">
Toggle theme
</button>
);
}There is a catch. The server renders the HTML before any script reads localStorage, so a dark-mode user sees a white flash on every load. The usual fix is a tiny inline script in the <head> that sets the class before the page paints, plus suppressHydrationWarning on <html> so React does not complain that the class differs from what the server sent. The popular next-themes package does exactly this for you, with a ThemeProvider set to attribute="class".
You can try the toggle itself here (the preview has no localStorage, so this version only toggles):
Preview
aria-pressed tells screen readers the button is a toggle and whether it is on. Add dark:text-indigo-300 to the heading and toggle again.
Fonts with next/font
next/font downloads a font at build time, serves it from your own domain and avoids layout shift while it loads. It also hands you a CSS variable, which is the bridge into Tailwind:
// app/layout.tsx
import { Inter, Fraunces } from "next/font/google";
const inter = Inter({ subsets: ["latin"], variable: "--font-inter" });
const fraunces = Fraunces({ subsets: ["latin"], variable: "--font-fraunces" });
export default function RootLayout({ children }: { children: React.ReactNode }) {
return (
<html lang="en" className={`${inter.variable} ${fraunces.variable}`}>
<body className="font-sans">{children}</body>
</html>
);
}/* app/globals.css */
@theme inline {
--font-sans: var(--font-inter);
--font-display: var(--font-fraunces);
}inter.variable is a generated class name that defines --font-inter on <html>. In @theme, --font-sans overrides Tailwind's default font-sans, and --font-display creates a new font-display utility. The inline keyword tells Tailwind to put the var(--font-inter) value straight into the utility instead of pointing at a theme variable on :root, which matters here because --font-inter lives on <html> via a class. Tailwind's docs recommend inline whenever a theme value refers to another variable.
shadcn/ui and headless libraries
Accessible menus, dialogs, tabs and comboboxes are hard: focus trapping, arrow keys, Escape to close, the right ARIA attributes. You should not write them from scratch. Two kinds of tools help.
Headless libraries give you the behaviour and accessibility with no styles at all. You add the Tailwind classes. Examples are Radix Primitives, Base UI, React Aria and Headless UI (made by the Tailwind team). They expose state through data attributes, which Tailwind can target directly: Radix sets data-state="open" on an open item, so data-[state=open]:rotate-180 flips a chevron.
shadcn/ui sits on top of a headless library (Radix or Base UI) and is not installed like a normal package. Running npx shadcn@latest add dialog copies the source of a styled Dialog component into your components/ui/ folder. From then on you own it: edit the classes, change the variants, delete what you do not need. Its components use cva, cn and CSS variable tokens in globals.css, so everything in this lesson is what you will find inside them.
Match each tool to what it gives you.
components/ui/button.tsx instead of node_modules?- App Router
- Next.js's
app/folder routing, where folders are URLs andlayout.tsxwraps the pages beneath it. - @tailwindcss/postcss
- Tailwind's PostCSS plugin, the usual way to add Tailwind v4 to Next.js.
- cva
- class-variance-authority: a library that maps variant props to class strings with types and defaults.
- @custom-variant
- A v4 directive that redefines or creates a variant, for example making
dark:follow a.darkclass. - next/font
- Next.js's font loader, which self-hosts fonts and exposes them as CSS variables.
- headless library
- A component library that provides behaviour and accessibility but no visual styles.
- shadcn/ui
- A collection of styled components you copy into your project and then own.