When working with Alpine JS, you are going to handle many conditions. You can have if-else conditions in Alpine JS with x-if
directive. On the official documentation about x-if
there is not much explanation. Here is an article if you are looking to add conditional classes in Alpine JS.
x-if
Direcitve in Alpine JS
You can use x-if
directive to conditionally render different sections of code on your web page. Here is a simple example of x-if
directive that checks whether the user is logged in.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 |
<div class="" x-data="{loggedIn:false}"> <template x-if="loggedIn"> <div> <h1> Welcome Back! </h1> <button @click="loggedIn=false">Logout</button> </div> </template> </div> |
x-else
Directive in Alpine JS
Unfortunately, there is no x-else
directive in Alpine JS, but you can use x-if
multiple times to handle conditions. The following code snippet displays a separate message if the user is not logged in.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 |
<div class="" x-data="{loggedIn:false}"> <template x-if="loggedIn"> <div> <h1> Welcome Back! </h1> <button @click="loggedIn=false">Logout</button> </div> </template> <template x-if="!loggedIn"> <div> <p>Please Login to Continue</p> <button @click="loggedIn=true">Login</button> </div> </template> </div> |
Multiple checks with x-if
Directive
You can add multiple checks using && , ||
operators. With these operators, you can handle any condition you want. The following code snippet checks if the logged-in user is an admin or a normal user.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 |
<div class="" x-data="{loggedIn:true, isAdmin:false, isUser:true}"> <template x-if="loggedIn && isAdmin"> <div> <h1> Welcome Back! You are Admin </h1> <button @click="loggedIn=false">Logout</button> </div> </template> <template x-if="loggedIn && isUser"> <div> <h1> Welcome Back! You are User </h1> <button @click="loggedIn=false">Logout</button> </div> </template> <template x-if="!loggedIn"> <div> <p>Please Login to Continue</p> <button @click="loggedIn=true">Login</button> </div> </template> </div> |
Conclusion
Alpine JS only has x-if
directive to use but you can utilize it to handle almost any possible conditions. With the help of && ||
operators, you can handle as many conditional renderings as you want.