4 min read
•Question 32 of 38hardWhat is Class Variance Authority (CVA)?
Building variant-driven component styles.
What You'll Learn
- What CVA solves
- Creating variants
- Compound variants
Install CVA
$ terminalBash
npm install class-variance-authorityBasic Usage
code.tsTypeScript
import { cva, type VariantProps } from 'class-variance-authority'
const button = cva(
'px-4 py-2 rounded font-medium transition-colors', // base
{
variants: {
intent: {
primary: 'bg-blue-500 text-white hover:bg-blue-600',
secondary: 'bg-gray-200 text-gray-900 hover:bg-gray-300',
danger: 'bg-red-500 text-white hover:bg-red-600',
},
size: {
sm: 'text-sm px-3 py-1',
md: 'text-base px-4 py-2',
lg: 'text-lg px-6 py-3',
},
},
defaultVariants: {
intent: 'primary',
size: 'md',
},
}
)React Component
code.txtTSX
type ButtonProps = VariantProps<typeof button> &
React.ButtonHTMLAttributes<HTMLButtonElement>
function Button({ intent, size, className, ...props }: ButtonProps) {
return (
<button className={button({ intent, size, className })} {...props} />
)
}
// Usage
<Button intent="danger" size="lg">Delete</Button>Compound Variants
code.tsTypeScript
const button = cva('...', {
variants: { ... },
compoundVariants: [
{
intent: 'primary',
size: 'lg',
className: 'uppercase tracking-wide',
},
],
})