Utilities
cn
A function that joins class names and removes the Tailwind classes that conflict.
Utilities
A function that joins class names and removes the Tailwind classes that conflict.
import * as React from 'react'
import { Checkbox, Label, cn } from 'ferry-ui'
export default function CnHero() {
const [selected, setSelected] = React.useState(true)
return (
<>
<div
className={cn(
'rounded-lg border bg-surface-100 px-4 py-3 text-sm text-foreground-light',
// A conditional class. When the condition is false, cn() ignores the value.
selected && 'border-primary-bright bg-primary-soft text-foreground',
)}
>
Customer portal
</div>
<Label>
<Checkbox checked={selected} onCheckedChange={(checked) => setSelected(checked === true)} />
Selected
</Label>
</>
)
}Import cn from the package root. Give it the class names in order. When two Tailwind classes set the same property, the last class stays.
import { cn } from 'ferry-ui'
cn('px-3 py-2', 'p-4') // 'p-4'
cn('text-sm', selected && 'text-foreground') // 'text-sm' when selected is falsecn for each className that has a condition.cn for each className that comes from two sources.cn is a plain function. A server component can call it.Write condition && 'class'. A value that is false, null or undefined adds no class.
cn also accepts arrays and objects. An object adds each key that has a true value.
cn('text-sm', ['font-medium', null], { 'text-destructive': true, 'opacity-50': false })
// 'text-sm font-medium text-destructive'Put the base classes first and className last. Then the caller can replace a base class.
import type { ComponentProps } from 'react'
import { cn } from 'ferry-ui'
// The base classes come first and `className` comes last: the class of the caller wins.
function Panel({ className, ...props }: ComponentProps<'div'>) {
return <div className={cn('rounded-lg border bg-surface-100 p-3 text-sm text-foreground', className)} {...props} />
}
export default function CnMerge() {
return (
<>
<Panel>The base padding</Panel>
<Panel className="p-6">More padding</Panel>
</>
)
}The ferry-ui components use the same rule. Your className comes last, and it wins.
cn(...inputs) returns one string of class names. It joins the values with clsx. Then it removes the conflicts with tailwind-merge.
| Parameter | Type | Role |
|---|---|---|
...inputs | ClassValue[] | The class names, in order. A value can be a string, an array, an object or an empty value. |