Learn x-if Statement in Alpinejs

In this section, we will learn if statements in Alpine.js, including how to use else statements with the not equal to (!=) operator. In Alpine.js, you can use only if statements within a template div.

Example 1

Simple use of x-if statement.

<div x-data="{show:true}">
    <template x-if="show">
        <div>Show Data if true</div>
    </template>
</div>

Example 2

If statement with click event.

<div x-data="{show:false}">
    <template x-if="show">
        <div>Show Data if true</div>
    </template>

    <button @click="show=false">Click</button>
</div>

Better way

<div x-data="{show:false}">
    <template x-if="show">
        <div>Show Data if true</div>
    </template>
    <button @click="show=!show">Click</button>
</div>

Example 3

In alpine js there is no else statement. But we perform operation else using (=!) not equal to.

<div x-data="{show:false}">
    <template x-if="show">
        <div>Show Data if true</div>
    </template>
    <template x-if="!show">
        <div>Show Data if false</div>
    </template>
</div>
Alpinejs x-if Statement

Example 4

if else with click event .

<div x-data="{show:false}">
    <template x-if="show">
        <div>Show Data if true</div>
    </template>
    <template x-if="!show">
        <div>Show Data if false</div>
    </template>
    <button @click="show=!show">Click</button>
</div>

Note: You can use x-show directive. x-show is much simple and easy to use, you can see same example in below.

<div x-data="{show:false}">
    <div x-show="show">
        <div>Show Data if true</div>
    </div>
    <div x-show="!show">
        <div>Show Data if false</div>
    </div>
    <button @click="show=!show">Click</button>
</div>
saim ansari
saim ansari

I'm Saim Ansari, a full-stack developer with 4+ years of hands-on experience who thrives on building web applications that leave a lasting impression. When it comes to tech, I'm particularly adept at Laravel, React, Tailwind CSS, and the Tall Stack