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, there is no clear way described in the documentation but you can do this 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. Let’s add a conditional class with an example.

 Adding a class with a 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 :class attribute in Alpine JS. 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.