cx

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

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

Usage

typescript
      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>
)
    
      const Button = ({ disabled, children }) => (
  <button
    // When rendered, the button will have class="button button--disabled"
    className={cx('button', disabled && 'button--disabled')}
    disabled={disabled}
  >
    {children}
  </button>
)
 
    
Created 09/05/21 • Updated 18/03/23