Course contentsShow
← React
Lesson 1937 of 2,39644. Styling ApproachesFree lesson

Style Variants Pattern

Using styleVariants() and recipe() to create configurable component styles with TypeScript-enforced variants.

Style Variants Pattern

What you'll learn: How to build flexible, type-safe component variants using styleVariants() and recipe() in vanilla-extract.

When building design systems, you often need components with multiple visual variations—think buttons with "primary", "secondary", and "danger" styles, or sizes like "small", "medium", and "large". Vanilla-extract provides two powerful tools for this: styleVariants() for simple variant mappings and recipe() for more complex, combinable variants.

Using styleVariants()

styleVariants() creates a mapped object of style variants from a single base style or independent definitions:

// button.css.ts
import { styleVariants } from '@vanilla-extract/css';

export const buttonSize = styleVariants({
  small: { padding: '8px 12px', fontSize: '14px' },
  medium: { padding: '12px 20px', fontSize: '16px' },
  large: { padding: '16px 28px', fontSize: '18px' }
});

Each key becomes a valid CSS class, fully typed. Your component gets autocomplete and type checking:

<button className={buttonSize.medium}>Click Me</button>

Using recipe()

For components needing multiple, combinable variants (color + size + state), use recipe():

import { recipe } from '@vanilla-extract/recipes';

export const button = recipe({
  base: { borderRadius: '4px', fontWeight: 600 },
  variants: {
    color: {
      primary: { backgroundColor: 'blue', color: 'white' },
      danger: { backgroundColor: 'red', color: 'white' }
    },
    size: {
      small: { padding: '8px 12px' },
      large: { padding: '16px 28px' }
    }
  },
  defaultVariants: {
    color: 'primary',
    size: 'small'
  }
});

// Usage with full TypeScript inference
<button className={button({ color: 'danger', size: 'large' })}>

Key Takeaway: Use styleVariants() for simple one-dimensional variations and recipe() for complex, multi-dimensional component APIs—both give you compile-time safety and excellent DX without runtime overhead.