Sub topic 8
Defining variants with cva
This chapter assumes you can read React function components and TypeScript generics. It also assumes you know Tailwind utility classes and have seen the cn helper from the previous chapter. By the end you will know how class-variance-authority (cva) maps component props to class strings, how it combines with cn, and where it commonly goes wrong.
The problem cva solves
A button usually comes in several visual forms: a primary fill, an outlined version, a small size, a large size. Without a helper, you end up with conditionals scattered through the JSX.
const classes =
variant === "outline"
? "border border-input bg-background"
: "bg-primary text-primary-foreground";This grows quickly. Every new prop multiplies the cases, and nothing ties the allowed values to the TypeScript types.
cva moves that logic into one declaration. You describe a base string, a set of named variants, and defaults. cva returns a function that takes props and returns a class string. It also exports a type helper so your component props stay in sync with the declaration.
Anatomy of a cva call
cva(base, config) takes two arguments. The base is a string of classes that always apply. The config is an object with these keys:
| Key | Purpose |
|---|---|
| `variants` | Maps each variant name to its allowed values and the classes for each value |
| `defaultVariants` | Values used when the caller omits a prop |
| `compoundVariants` | Extra classes applied only when a combination of values matches |
The button from shadcn/ui shows the first two:
import { cva } from "class-variance-authority"
const buttonVariants = cva(
"inline-flex items-center justify-center rounded-md text-sm font-medium transition-colors focus-visible:outline-none focus-visible:ring-2 disabled:pointer-events-none disabled:opacity-50",
{
variants: {
variant: {
default: "bg-primary text-primary-foreground hover:bg-primary/90",
outline: "border border-input bg-background hover:bg-accent",
},
size: {
default: "h-10 px-4 py-2",
sm: "h-9 px-3",
},
},
defaultVariants: { variant: "default", size: "default" },
}
)Calling buttonVariants({ variant: "outline", size: "sm" }) returns the base classes, then the outline classes, then the sm classes, joined into one string. Calling buttonVariants() with no arguments uses the defaults.
The base string holds everything that does not change between variants: layout, typography, focus ring, and disabled styling. Keeping the disabled and focus rules in the base means every variant gets accessible states without repeating them.
How the resolution works
When you call the generated function, cva does the following:
- Starts with the base string.
- For each variant name, reads the prop you passed. If it is
undefined, it uses the entry fromdefaultVariants. - Looks up the class string for that value and appends it.
- Checks each compound variant and appends its classes if every condition matches.
- Appends any
classorclassNameyou passed to the function.
Notice what cva does not do. It joins strings. It does not detect that px-4 and px-3 conflict. That is the job of cn, which is why the two are used together.
Typing props with VariantProps
VariantProps<typeof buttonVariants> extracts the prop types from the declaration. If you add a lg size later, the type updates without any manual edit.
import * as React from "react"
import { Slot } from "@radix-ui/react-slot"
import { cva, type VariantProps } from "class-variance-authority"
import { cn } from "@/lib/utils"
const buttonVariants = cva(
"inline-flex items-center justify-center rounded-md text-sm font-medium transition-colors focus-visible:outline-none focus-visible:ring-2 disabled:pointer-events-none disabled:opacity-50",
{
variants: {
variant: {
default: "bg-primary text-primary-foreground hover:bg-primary/90",
outline: "border border-input bg-background hover:bg-accent",
},
size: {
default: "h-10 px-4 py-2",
sm: "h-9 px-3",
},
},
defaultVariants: { variant: "default", size: "default" },
}
)
export interface ButtonProps
extends React.ButtonHTMLAttributes<HTMLButtonElement>,
VariantProps<typeof buttonVariants> {
asChild?: boolean
}
const Button = React.forwardRef<HTMLButtonElement, ButtonProps>(
({ className, variant, size, asChild = false, ...props }, ref) => {
const Comp = asChild ? Slot : "button"
return (
<Comp
className={cn(buttonVariants({ variant, size }), className)}
ref={ref}
{...props}
/>
)
}
)
Button.displayName = "Button"
export { Button, buttonVariants }Three details matter here.
variantandsizeare destructured out of the props so they are not forwarded to the DOM element. If they reached a<button>, React would pass unknown attributes through and you would get invalid markup.classNameis passed tocnafter the variant classes. Becausetailwind-mergekeeps the last of two conflicting utilities, a caller'sclassName="h-12"overrides the variant'sh-10.buttonVariantsis exported. Other code can apply the same styles to a different element, such as a link.
With the types in place, an invalid value is a compile error:
<Button variant="outline" size="sm">Save</Button>
<Button variant="ghost">Oops</Button> {/* Type error: "ghost" is not defined */}Adding variants and sizes
Because you own the file, adding a variant is an edit to the object. Here is a destructive variant and a lg size:
variants: {
variant: {
default: "bg-primary text-primary-foreground hover:bg-primary/90",
destructive: "bg-destructive text-destructive-foreground hover:bg-destructive/90",
outline: "border border-input bg-background hover:bg-accent",
},
size: {
default: "h-10 px-4 py-2",
sm: "h-9 px-3",
lg: "h-11 px-8",
},
},The color names such as bg-destructive come from the CSS variable theme covered in the theming chapter. Using semantic names instead of raw colors means a theme change updates every variant at once.
Compound variants
Sometimes a rule depends on two props together. A compound variant applies extra classes only when all its conditions match.
import { cva } from "class-variance-authority"
const badge = cva("inline-flex items-center rounded-full text-xs font-semibold", {
variants: {
tone: {
neutral: "bg-muted text-foreground",
danger: "bg-destructive text-destructive-foreground",
},
interactive: {
true: "cursor-pointer",
false: "",
},
},
compoundVariants: [
{
tone: "danger",
interactive: true,
class: "hover:bg-destructive/90",
},
],
defaultVariants: { tone: "neutral", interactive: false },
})
console.log(badge({ tone: "danger", interactive: true }))The hover rule appears only for an interactive danger badge. A neutral interactive badge does not get it. Without compound variants you would write that check in JSX.
Boolean-style variants use the keys true and false. You can then pass a real boolean, interactive, rather than a string. Compound variants also accept an array of values, such as tone: ["danger", "neutral"], to match any of them.
Edge cases and common errors
Class conflicts between variants. If two variants set the same property, such as size setting px-4 and a compound rule setting px-6, cva appends both and the browser decides by CSS order, not by string order. Wrap the call in cn so tailwind-merge keeps the later one. In shadcn/ui components, this is already the pattern, but a direct call to buttonVariants() in your own code does not merge anything.
Dynamic class names break Tailwind. Tailwind finds classes by scanning source text. Writing ` bg-${color}-500 ` produces a string the scanner cannot see, and the style is never generated. Write each full class name as a literal inside the variants object, as the examples do.
Forgetting defaults. If you omit defaultVariants, calling <Button /> with no props produces only the base classes and no fill or size. The type allows this because the props are optional. Set defaults for every variant that should always have a value.
Passing null. In cva, null means "apply nothing for this variant", while undefined means "use the default". If a prop can arrive as null from an API, convert it with ?? undefined when you want the default.
Variants that should be separate components. If a "variant" changes the element's structure, not just its styling, such as adding an icon slot or a different child layout, a variant is the wrong tool. Make a separate component or use composition with asChild.
Too many axes. Each variant axis multiplies the states you must test and document. Three axes of three values each give twenty-seven combinations. Add an axis only when callers genuinely need it, and prefer one-off className overrides for rare cases.
Using the variants function on its own
Because buttonVariants is exported, you can style a link like a button without wrapping it in Button:
import { buttonVariants } from "@/components/ui/button"
import { cn } from "@/lib/utils"
export function DocsLink() {
return (
<a href="/docs" className={cn(buttonVariants({ variant: "outline" }), "w-full")}>
Read the docs
</a>
)
}This keeps one source of truth for button styling. The alternative, <Button asChild><a href="/docs">...</a></Button>, produces the same result through the Slot and is covered in the composition chapter. Calling the function directly works with any element and needs no Radix dependency in the caller.
Exercise
A teammate writes <Button className="px-8" size="sm">. The sm size sets px-3. Which padding applies, and which part of the setup guarantees it? What would change if the component called buttonVariants(...) without cn?
Show answer
The px-8 padding applies. The component passes buttonVariants({ variant, size }) and then className to cn, and tailwind-merge inside cn drops the earlier conflicting px-3 and keeps the later px-8. cva alone only joins strings, so without cn both px-3 and px-8 would remain in the class attribute, and the winner would depend on the order of rules in the generated CSS, not on the order in the string.
Exercise
Write a cva declaration for an alert with a status variant (info, error) defaulting to info, and a boolean dismissible variant. When status is error and dismissible is true, add the class pr-10. Which key holds that rule?
Show answer
Use compoundVariants.
const alert = cva("rounded-md border p-4 text-sm", {
variants: {
status: { info: "bg-muted", error: "bg-destructive text-destructive-foreground" },
dismissible: { true: "relative", false: "" },
},
compoundVariants: [{ status: "error", dismissible: true, class: "pr-10" }],
defaultVariants: { status: "info", dismissible: false },
})