cn

Utility for merging Tailwind CSS classes with conflict resolution.

The cn utility merges Tailwind CSS class names intelligently, handling conflicts and conditional classes.

Usage

import { cn } from "@tilt-legal/cubitt-components/utilities";

// Basic merging
cn('px-2 py-1', 'px-4')                    // "py-1 px-4" (px-4 wins)

// Conditional classes
cn('text-base', isLarge && 'text-lg')      // "text-lg" (if isLarge is true)

// Array of classes
cn(['px-2', 'py-1'], 'rounded')            // "px-2 py-1 rounded"

// With objects
cn('px-2', { 'py-4': true, 'py-2': false }) // "px-2 py-4"

How it works

Built on top of clsx and tailwind-merge, the cn utility:

  1. Uses clsx to handle conditional classes, arrays, and objects
  2. Uses tailwind-merge to resolve Tailwind class conflicts (later classes override earlier ones)

Common Use Cases

Component Variants

function Button({ size, className, ...props }) {
  return (
    <button
      className={cn(
        'rounded font-medium',
        size === 'sm' && 'px-3 py-1 text-sm',
        size === 'lg' && 'px-6 py-3 text-lg',
        className
      )}
      {...props}
    />
  );
}

<Button size="lg" className="bg-blue-500" />
// Results in: "rounded font-medium px-6 py-3 text-lg bg-blue-500"

Conditional Styling

<div className={cn(
  'p-4 rounded',
  isActive && 'bg-blue-500 text-white',
  isDisabled && 'opacity-50 cursor-not-allowed'
)} />

Overriding Defaults

function Card({ className, ...props }) {
  return (
    <div
      className={cn(
        'p-6 bg-white rounded-lg shadow',
        className  // User can override any default
      )}
      {...props}
    />
  );
}

<Card className="bg-gray-100 p-8" />
// Results in: "rounded-lg shadow bg-gray-100 p-8"
// (bg-gray-100 overrides bg-white, p-8 overrides p-6)

On this page