content/docs/api/cn.mdx
@udecode/cn provides class-name helpers and component wrappers for React UI primitives. The package also re-exports @udecode/react-utils from its root entry.
npm install @udecode/cn
import * as React from 'react';
import { cn, withCn, withProps, withVariants } from '@udecode/cn';
const active = true;
const className = cn('px-2', active && 'bg-accent', 'px-4');
const ButtonBase = React.forwardRef<
HTMLButtonElement,
React.ComponentProps<'button'>
>((props, ref) => <button ref={ref} {...props} />);
const Button = withCn(ButtonBase, 'inline-flex items-center rounded-md');
const PrimaryButton = withProps(Button, {
type: 'button',
className: 'bg-primary text-primary-foreground',
});
| Surface | Owner | What It Does |
|---|---|---|
cn | @udecode/cn | Combines class-variance-authority cx with tailwind-merge. |
withCn | @udecode/cn | Creates a component with a default merged className. |
withProps | @udecode/cn | Creates a forwardRef component with default props. |
withVariants | @udecode/cn | Creates a forwardRef component that computes classes from cva variants. |
| React utility exports | @udecode/react-utils | Re-exported from the @udecode/cn root entry. |
| Helper | Behavior |
|---|---|
cn(...inputs) | Runs values through cx, then resolves Tailwind conflicts with twMerge. |
withCn(Component, ...inputs) | Calls withProps with a default className created from cn. |
withProps(Component, defaultProps) | Merges default props first and consumer props second. |
withProps class names | Merges defaultProps.className and props.className with cn. |
withProps refs | Returns React.forwardRef. |
withVariants(Component, variants, onlyVariantsProps?) | Applies variants(variantProps) and merges the result with className. |
onlyVariantsProps | Removes variant-only props from the rendered component props. |
cnMerge conditional class values and resolve Tailwind conflicts.
cn('px-2', active && 'bg-accent', 'px-4');
withCnCreate a component with default classes.
const Card = withCn('div', 'rounded-md border bg-card');
withPropsCreate a component with default props. Consumer props override default props, except class names are merged.
const SubmitButton = withProps('button', {
type: 'submit',
className: 'font-medium',
});
withVariantsCreate a component backed by class-variance-authority variants.
import { cva } from 'class-variance-authority';
const buttonVariants = cva('inline-flex items-center', {
variants: {
size: {
sm: 'h-8 px-2',
md: 'h-9 px-3',
},
},
});
const Button = withVariants('button', buttonVariants, ['size']);