Course contentsShow
← React
Lesson 1905 of 2,39644. Styling ApproachesFree lesson

Dynamic Class Names with clsx

Combining static and conditional class names using the clsx or classnames library for cleaner JSX.

Dynamic Class Names with clsx

What you'll learn: How to cleanly combine static and conditional class names using the clsx library instead of messy string concatenation in your JSX.


When you're using CSS Modules (or any CSS approach), you often need to apply multiple class names conditionally—like a base style plus an "active" variant, or adding "disabled" only when certain props are true. Without a helper library, this gets ugly fast: className={styles.button{styles.button} {isActive ? styles.active : ''} ${disabled ? styles.disabled : ''}}.

This is where clsx (or its predecessor classnames) shines. It's a tiny utility that intelligently combines class names, ignoring falsy values:

import clsx from 'clsx';
import styles from './Button.module.css';

function Button({ isActive, disabled, children }) {
  return (
    <button
      className={clsx(
        styles.button,           // always applied
        isActive && styles.active, // only if isActive is true
        disabled && styles.disabled // only if disabled is true
      )}
    >
      {children}
    </button>
  );
}

You can also pass objects where keys are class names and values are conditions:

className={clsx(styles.button, {
  [styles.active]: isActive,
  [styles.disabled]: disabled
})}

Think of it like a smart filter: clsx takes all your class name candidates—some strings, some conditionals—and outputs only the valid ones as a clean space-separated string. No more empty strings, extra spaces, or ternary soup cluttering your JSX.

This pairs perfectly with CSS Modules because you're juggling local class names from styles objects. The result is readable, maintainable conditional styling.

Key Takeaway: Use clsx to combine static and conditional class names cleanly—it handles falsy values and keeps your JSX focused on logic, not string manipulation.