In this Alpine.js tutorial, we will explore x-show. x-show is one of the most useful and powerful directives in Alpine.js. It allows you to show and hide DOM elements based on a condition. By default, x-show applies display: none; style to elements depending on whether the expression resolves to true or false. If true, the elements will be shown; if false, they will be hidden. Let's explore some examples.
Example 1
It will not show because the show value is false, which means its style is set to display: none
.
<div x-data="{ show: false }">
<p x-show="show">not show if false</p>
<p> <strong x-text="show"></strong> </p>
</div>
To Show
if you want to show you need to give show value true.
<p x-show="show = true">not show if false</p>
or
<p x-show="!show">not show if false</p>
Warning ⚠️
if you are using two elements at the same time print then both will be true to avoid problem you need to opposite(!).
<div x-data="{ show: false }">
<p x-show="show">not working !</p>
<p x-show="show = true">It working !</p>
<p> <strong x-text="show"></strong> </p>
</div>
<div x-data="{ show: false }" class="text-center">
<p x-show="show">not working !</p>
<p x-show="!show">It working !</p>
<p> <strong x-text="show"></strong> </p>
</div>
Example 2
If you want to show element one time at click.
<div x-data="{ show: false }">
<button x-on:click="show = true">show</button>
<p x-show="show">show Paragraph</p>
</div>
Do This ✅
If you want to show and hide then use = ! it react opposite value.
<div x-data="{ show: false }">
<button x-on:click="show = !show">show</button>
<p x-show="show">show Paragraph</p>
</div>
For much better Do This ✅
if you want show and hide with button value then do this.
<div x-data="{ show: false }">
<button x-on:click="show = !show" x-text="!show ? 'Show' : 'Hide'">show</button>
<p x-show="show">show Paragraph</p>
</div>
Use of x-show
We can use x-show in many places, such as:
Showing and hiding modals
Creating dropdowns and toggles
Implementing FAQ sections
Designing responsive navbars
Top comments (0)