cx

A tiny helper function to conditionally join classnames. Simplified version of JedWatson's classnames and lukeed's clsx.

typescriptjavascript
export const cx = (...classes: (string | boolean | null | undefined)[]) =>
classes.filter(cls => typeof cls === 'string').join(' ')

Usage

tsxjsx
const Button: React.FC<{ disabled?: boolean }> = ({ disabled, children }) => (
<button
// When rendered, the button will have class="button button--disabled"
className={cx('button', disabled && 'button--disabled')}
disabled={disabled}
>
{children}
</button>
)
Created 05/09/21Updated 03/18/23
Found a mistake, or want to suggest an improvement? Edit on GitHub here
and see edit history here