Using clsx to Organize Our Tailwind Classes
Haikel, 2 min read / January 2, 2023
بِسْمِ اللَّهِ الرَّحْمَٰنِ الرَّحِيمِ
clsx
is an utility for constructing className strings. You can see the repository Here. We often see clsx
are used to manage Tailwind Classes.
Installation
Depending on what package manager you use. I'm using yarn, so i can type:
yarn add clsx
Example
Let's say we want set display to flex while isActive
is true, and hidden while isActive
is false.
<div
className={`${
isActive ? "flex" : "hidden"
} items-center justify-center border-2 border-black px-4 py-2`}
>
<p className="font-semibold">Contoh</p>
</div>
In this case, we can use clsx
.
<div
className={clsx(
isActive ? "flex" : "hidden",
"items-center justify-center border-2 border-black px-4 py-2"
)}
>
<p className="font-semibold">Contoh</p>
</div>
Another example, we want to create a button like this:
<button className="rounded-md bg-blue-500 px-4 py-2 font-semibold text-white transition-all hover:bg-blue-500">
Contoh
</button>
Looks long, right? Well, we can use clsx
to organize it.
<button
className={clsx(
"rounded-md bg-blue-500 px-4 py-2",
"font-semibold text-white transition-all",
"hover:bg-blue-500"
)}
>
Contoh
</button>
When to use clsx
?
- If we need a class or some classes that will set only in certain conditions(actually, we can just use template literals, but with
clsx
, the classes will more readable and organize). - If classes is already looks long.