Skip to content

The Tailwind "cn" Utility

Published:

hpc featured

When working with Tailwind CSS, you often need to conditionally apply multiple classes. This is where the “cn” utility (short for “class names”) comes in handy. Here’s a breakdown of why it’s so useful:

Table of contents

Open Table of contents

The code

// cn.ts
import type { ClassValue } from "clsx";

import { clsx } from "clsx";
import { twMerge } from "tailwind-merge";

export const cn = (...inputs: ClassValue[]) => {
  return twMerge(clsx(inputs));
};

The Utility Simplifies Conditional Class Logic

In many projects, especially when working with frameworks like React, you need to dynamically apply classes based on conditions. Without a utility like "cn", this can result in messy and hard-to-read code, with multiple ternary operators or array joins.

Using "cn", you can easily toggle classes in a cleaner way:

import { cn } from "@/utils"; // Assuming you have a utility folder

const buttonClasses = cn(
  "px-4 py-2 text-white",
  isPrimary ? "bg-blue-500" : "bg-gray-500",
  isDisabled && "opacity-50 cursor-not-allowed"
);

This improves readability by organizing the logic and reducing code clutter.

Handles Falsy Values Gracefully

One of the best features of the "cn" utility is that it automatically skips falsy values like false, undefined, or null. You don’t have to worry about conditionally adding classes that don’t apply—"cn" does it for you.

const alertClasses = cn(
  "p-4 border",
  alertType === "error" && "bg-red-500 border-red-700",
  isVisible && "block"
);

In this example, if isVisible is false, the "block" class won’t be added, simplifying logic without extra conditionals.

As an aside, while the above syntax is correct, my preferred style would be to use the object syntax for handling conditional classes:

const alertClasses = cn("p-4 border", {
  "bg-red-500 border-red-700": alertType === "error",
  block: isVisible,
});

Improvements to the Developer Experience

By reducing conditional logic and improving code readability, "cn" enhances the overall developer experience. When building out complex UIs, especially with components that have a lot of conditional styling, "cn" keeps your codebase clean and easy to maintain.

Conclusion

If you’re using Tailwind in your project, adding a utility like "cn" can save time and make your class management much more straightforward. Cleaner code, fewer bugs, and better readability—it’s a simple but powerful tool that helps you write better Tailwind CSS.

Source(s)