Sub topic 2
Setting Up shadcn/ui and Adding Components
Assume you know React function components, basic TypeScript, Tailwind CSS utilities, npm, and how to run a Vite or Next.js project. shadcn/ui is a collection of component source files that you add to your project. You own the files and can edit them.
Setting Up the CLI and Adding Components
Run the CLI from your project directory:
npx shadcn@latest init
npx shadcn@latest add button dialogThe init command configures the project and creates components.json. The add command copies the selected component source into your codebase. It may also install dependencies such as Radix UI primitives.
Merging Class Names with `cn`
A component often has default classes and accepts a caller-provided className. The cn helper combines conditional classes with clsx, then uses tailwind-merge to remove conflicting Tailwind utilities.
import { clsx, type ClassValue } from "clsx"
import { twMerge } from "tailwind-merge"
export function cn(...inputs: ClassValue[]) {
return twMerge(clsx(inputs))
}For example, cn("px-4", "px-6") returns a class string where the later padding utility wins.
Defining Variants with `cva`
class-variance-authority, usually called CVA, defines named style options. This keeps combinations such as variant="outline" and size="sm" predictable.
import { cva } from "class-variance-authority"
export const buttonVariants = cva("rounded-md font-medium", {
variants: {
variant: {
default: "bg-primary text-primary-foreground",
outline: "border border-input bg-background",
},
size: {
default: "h-10 px-4",
sm: "h-9 px-3",
},
},
defaultVariants: { variant: "default", size: "default" },
})Use cn(buttonVariants({ variant, size }), className) when rendering the component.
Theming with CSS Variables and Dark Mode
shadcn/ui commonly stores semantic colors in CSS variables. Components use names such as bg-primary instead of hard-coded colors. A .dark class can provide alternate values.
:root {
--primary: 222 47% 11%;
--primary-foreground: 210 40% 98%;
}
.dark {
--primary: 210 40% 98%;
--primary-foreground: 222 47% 11%;
}Configure Tailwind to map these variables to color utilities. Changing the class on an ancestor, often <html>, changes the theme without editing each component.
> callout note > Keep variable names semantic. --primary communicates intent, while --blue-700 ties components to one visual choice.
Exercise
What does shadcn add button place in your project, and why is that different from installing only a component package?
Show answer
It copies editable component source into your project, so you own and can customize the implementation.