Day 1 – Learning a Utility Function for Tailwind Classes
Today I started working on the Build Shop project, full-stack web marketplace platform designed for the construction industry
Project repository:
https://github.com/cheaven8/build-shop
While exploring the project, I came across a small utility function that helps manage CSS classes when using Tailwind. At first it looked simple, but it actually solves a common problem in frontend development.
Here is the code:
import { clsx, type ClassValue } from "clsx";
import { twMerge } from "tailwind-merge";
export function cn(...inputs: ClassValue[]) {
return twMerge(clsx(inputs));
}
What Problem Does This Solve?
When building UI components, especially with Tailwind CSS, we often need to combine multiple class names dynamically.
For example:
- Some classes depend on conditions
- Some come from component props
- Some might override others
If we just concatenate strings, the code becomes messy and sometimes conflicting Tailwind classes appear.
Example problem:
"p-2 p-4 text-red-500"
Here both p-2 and p-4 exist, but Tailwind should only apply the last one.
This is where clsx and tailwind-merge help.
Understanding Each Part
1. clsx
clsx is a small utility for conditionally joining class names.
Example:
clsx("btn", true && "active", false && "hidden")
Result:
"btn active"
It ignores false values and merges valid class names.
2. tailwind-merge
tailwind-merge solves Tailwind conflicts.
Example:
twMerge("p-2 p-4")
Result:
"p-4"
It removes conflicting Tailwind classes and keeps the correct one.
3. The cn() Function
The cn function combines both tools:
-
clsx()merges class names -
twMerge()resolves Tailwind conflicts
Example:
cn("p-2", "p-4", "text-red-500")
Result:
"p-4 text-red-500"
This makes it perfect for React or component-based projects.
Why This Pattern Is Popular
Many modern React projects use this helper because it:
- Keeps components clean
- Prevents Tailwind class conflicts
- Makes conditional styling easier
You will often see this function in projects built with Next.js, ShadCN UI, or modern Tailwind setups.
What I Learned Today
From this small utility function, I learned:
- How to manage dynamic class names
- Why Tailwind classes sometimes conflict
- How libraries like
clsxandtailwind-mergesimplify UI development
Even though the function is only a few lines long, it improves developer experience a lot.
Small utilities like this make large projects easier to maintain.
Looking forward to learning more tomorrow.
Top comments (0)