How to Add Conditional Classes in Alpine JS

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.

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.

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.

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.

Latest articles

Related articles