# Dynamic Classes & tailwind-merge

> Simple string concatenation breaks in CSS cascade order; combine clsx for conditional logic with tailwind-merge (cn) to resolve utility collisions reliably.

Subject: Tailwind CSS | Lesson 15 of 16 | 8 min read
Interactive lesson: https://codewithanimation.in/tailwind/dynamic-classes-and-merge
Previous: [Extracting Components](https://codewithanimation.in/tailwind/extracting-components.md) | Next: [Dark Mode Strategy](https://codewithanimation.in/tailwind/dark-mode-strategy.md)

## What Dynamic Class Merging and tailwind-merge Are

Dynamic class merging is the process of conditionally applying and overriding Tailwind utility classes in React components based on state or props.

Simple string concatenation (e.g. `"bg-sky-600 " + (isRed ? "bg-rose-600" : "")`) fails because browser CSS precedence depends on stylesheet rule order, not the order class names appear in the HTML `class` attribute.

The `clsx` library formats conditional class strings, while `tailwind-merge` (`twMerge`) intelligently detects and resolves conflicting Tailwind utility classes.

The standard `cn(...)` helper function combines `twMerge(clsx(...))` into a single unified utility merger.

## Why Naive String Concatenation Fails and tailwind-merge is Required

Understanding utility class collision resolution prevents silent styling bugs in dynamic components:

1. The CSS Cascade Order Trap: If a component outputs `<button class="bg-sky-600 bg-rose-600">`, the winning color is determined by which rule appears later in Tailwind's compiled CSS stylesheet. Ordering in string concatenation does NOT guarantee visual precedence.

2. clsx Does Not Resolve Collisions: The `clsx` package formats objects and conditional arrays into a single string. However, `clsx("bg-sky-600", "bg-rose-600")` simply outputs `"bg-sky-600 bg-rose-600"`, leaving utility conflicts unresolved.

3. Intelligent Overrides with tailwind-merge: `twMerge` understands Tailwind property groups. It recognizes that `bg-rose-600` overrides `bg-sky-600` or `px-4` overrides `p-2` on horizontal axes, stripping the overridden class from the DOM string.

## How to Implement the Universal cn() Helper in React

Follow these standard steps to set up and use `cn()` across your codebase:

1. Install Dependencies: Add `clsx` and `tailwind-merge` to your project dependencies (`npm i clsx tailwind-merge`).

2. Create the Helper Module: Export `cn(...)` from a helper file (e.g. `src/lib/utils.ts`): `export function cn(...inputs: ClassValue[]) { return twMerge(clsx(inputs)); }`.

3. Apply in Components: Pass base styles, conditional expressions, and caller `className` props directly to `cn()` in your components: `className={cn("px-4 py-2 bg-sky-600", isDestructive && "bg-rose-600", className)}`.

## Common mistake: String Interpolation of Dynamic Utility Names

A frequent beginner mistake is attempting to construct class names dynamically using string templates like `bg-${color}-500` or `text-${size}`.

Tailwind CSS scans source code statically at build time for complete, un-truncated class strings.

Constructing class names dynamically prevents Tailwind's compiler from detecting the class. Always use complete class literals (`color === 'red' ? 'bg-red-500' : 'bg-blue-500'`) or lookup maps.

## Tip: Handling Directional Shorthand Overrides with twMerge

Notice how `twMerge('p-4 px-2')` outputs `'p-4 px-2'`. `twMerge` understands that `px-2` only overrides horizontal padding, preserving vertical padding from `p-4`.

This granular property awareness ensures that component consumers can override specific axes without breaking surrounding component spacing.

## Try it: Dynamic Class & Utility Merger Lab

Test interactive toggles to compare standard string concatenation, clsx formatting, and intelligent twMerge collision resolution in real time.

The animation is on the lesson page and is not part of this text version: https://codewithanimation.in/tailwind/dynamic-classes-and-merge

## Check yourself

### Question 1

Why does className='bg-sky-600 bg-rose-600' fail to reliably display a rose background on a button?

- A. Browser CSS precedence depends on stylesheet rule order in compiled CSS, not class name order in the HTML attribute
- B. Tailwind disables elements that contain two background color utilities
- C. HTML class attributes only accept one background color utility at a time

Correct answer: A

Browser CSS cascade priority is determined by the order rules are declared in the stylesheet, not the string order inside HTML class attributes.

- Why not B: Tailwind compiles valid CSS rules; collision resolution is handled by standard browser cascade.
- Why not C: HTML class attributes accept any string; the issue is CSS stylesheet rule cascade order.

### Question 2

What is the difference between clsx and tailwind-merge (twMerge)?

- A. clsx joins conditional class strings, while twMerge parses Tailwind utility categories and removes conflicting classes
- B. clsx is for React, while twMerge is strictly for Vue and Svelte
- C. twMerge formats objects, while clsx resolves background color conflicts

Correct answer: A

clsx formats conditional arrays and objects into class strings. twMerge parses Tailwind property groups to strip overridden utilities.

- Why not B: Both clsx and twMerge are framework-agnostic JavaScript utilities.
- Why not C: Role is inverted: clsx handles object/array string formatting; twMerge resolves Tailwind utility collisions.

### Question 3

Why does className={`bg-${color}-500`} fail to apply styles in production Tailwind builds?

- A. Tailwind relies on build-time static extraction and cannot detect string-interpolated partial class names
- B. Template literals are unsupported in JSX class attributes
- C. Dynamic colors require inline style attributes in React

Correct answer: A

Tailwind's static scanner looks for exact, complete class strings at build time. Interpolated strings like bg-${color}-500 are not detected.

- Why not B: Template literals are valid JavaScript syntax in JSX.
- Why not C: Complete Tailwind utility literals work in JSX without inline styles.

## Remember this

- Never rely on HTML class attribute string order to resolve utility collisions.
- clsx cleanly formats conditional class arrays and objects into strings.
- tailwind-merge (twMerge) removes conflicting Tailwind utilities based on CSS property semantics.
- Use export function cn(...inputs) { return twMerge(clsx(inputs)); } as your universal class merger.
- Avoid string interpolation like bg-${color}-500; always use complete utility class literals.
