cn utility
A tiny helper, cn(...classes) = twMerge(clsx(classes)), that joins class names conditionally and then removes conflicting Tailwind classes.
In more detail
Components wrap their own classes and the caller's className in cn, so a caller's px-8 reliably replaces the component's px-3. Without it both classes would be present and the winner would depend on stylesheet order.
Example
cn(button({ size: "sm" }), "px-8") keeps px-8 and drops the variant's px-3.Related terms
- clsx — A tiny JavaScript function that builds a class string from strings, objects and conditions, skipping anything falsy.
- tailwind-merge — A JavaScript library that removes Tailwind classes overridden by later ones in the same list, such as dropping p-4 when px-6 follows.
- className — The React prop, and DOM property, that sets an element's HTML class attribute.
- Class Variance Authority — A small JavaScript library that turns a component's variants, such as intent and size, into the right list of CSS classes.
Taught in
- Class Variance Authority: Type-Safe Variant & Prop Orchestration — Design Systems & Component Engineering
- Polymorphism & Slotted Composition: The asChild Pattern — Design Systems & Component Engineering