In Alpine JS, there are many use cases where you want to conditionally add classes to elements. Unfortunately, the official documentation is a bit confusing when explaining that x-bind stuff, but you can add a conditional class with a simple :class
attribute.
Adding Classes Based on a condition with Alpine JS
The general syntax to add classes with a condition is described below.
1 2 3 4 5 6 7 8 9 |
<div x-data="{open:true}"> <h1 class="text-2xl font-bold" :class="{ 'bg-green-500': open }"> TailwindCSS with Alpine JS </h1> </div> |
The above example will add bg-green-500
class when the open is true.
Adding At Least One Class Conditionally in Alpine JS
You can also add the else
part if you wish to use another class conditionally. The following example adds bg-green-500
if the open
is true otherwise, it will add bg-red-500
class.
1 2 3 4 5 6 7 8 9 |
<div x-data="{open:true}"> <h1 class="text-2xl font-bold" :class="open ? 'bg-green-500' : 'bg-red-500'"> TailwindCSS with Alpine JS </h1> </div> |
Now, let’s use a button to add a new class when it’s clicked.
Adding a Class with a Button Click in Alpine JS
Here is a simple button that will change the open value when it’s clicked. The open condition will add or remove the class bg-green-500. You can see the rest of the classes are separate with another class attribute.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 |
<div class="mx-auto mt-20 flex w-1/2 flex-col items-center justify-center" x-data="{open:false}" x-cloak > <h1 class="text-2xl font-bold" :class=" { 'bg-green-500': open }" > TailwindCSS with Alpine JS </h1> <div class="mt-10"> <button x-on:click="open=!open" class="rounded-md bg-blue-600 px-4 py-2 text-center text-white" > Change Background </button> </div> </div> |
Conclusion
You can add or remove classes with a condition using x-bind
attribute. The shorthand syntax is to use :class
. When the condition you write in :class
attribute is true, the classes will be added, and if it’s false, the class will be removed.