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.

Frequently asked questions

How does React handle clsx?
React covers this with 2 copy-ready snippets on this page. The "className Patterns" snippet in React uses `<div className="static-class" />`.
Which code does the React example use?
The "className Patterns" snippet uses `<div className="static-class" />`, from the Styling section of the React cheat sheet.
What other React snippets are shown for "clsx"?
Besides "className Patterns", this page also shows "Conditional Classes".
Is there anything to watch out for?
Yes. For "className Patterns": 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.