Clsx

2 snippets in React

REReact

className Patterns

RE · Styling
syntax
<div className="static-class" />
<div className={dynamicVariable} />
<div className={`base ${condition ? 'active' : ''}`} />
example
function NavLink({ href, isActive, children }) {
  // Template literal approach
  const className = `nav-link ${isActive ? 'nav-link--active' : ''}`;

  return <a href={href} className={className}>{children}</a>;
}

// Helper function for multiple conditional classes
function classNames(...classes) {
  return classes.filter(Boolean).join(' ');
}

function Card({ featured, compact, className }) {
  return (
    <div
      className={classNames(
        'card',
        featured && 'card--featured',
        compact && 'card--compact',
        className
      )}
    >
      {/* ... */}
    </div>
  );
}

Note Use a small classNames helper or the popular 'clsx' package to compose conditional classes cleanly. Avoid complex ternary chains inside className attributes -- extract the logic to keep JSX readable.

Conditional Classes

RE · Styling
syntax
// With clsx or classnames library
import clsx from 'clsx';
<div className={clsx('base', { active: isActive, disabled: isDisabled })} />
example
// Using the clsx library
import clsx from 'clsx';

function StatusChip({ status }) {
  return (
    <span
      className={clsx('chip', {
        'chip--success': status === 'active',
        'chip--warning': status === 'pending',
        'chip--danger': status === 'error',
        'chip--muted': status === 'inactive',
      })}
    >
      {status}
    </span>
  );
}

// Without a library
function StatusChipManual({ status }) {
  const chipClass = [
    'chip',
    status === 'active' && 'chip--success',
    status === 'error' && 'chip--danger',
  ].filter(Boolean).join(' ');

  return <span className={chipClass}>{status}</span>;
}

Note The clsx library (or classnames) accepts strings, objects, and arrays. Object keys are included when their value is truthy. It is lightweight (~228 bytes) and widely used in the React ecosystem.