
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 todisplay: none
.
<divx-data="{ show: false }"><px-show="show">not show if false</p><p><strongx-text="show"></strong></p></div>
To Show
if you want to show you need to give show value true.
<px-show="show = true">not show if false</p>
or
<px-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(!).
<divx-data="{ show: false }"><px-show="show">not working !</p><px-show="show = true">It working !</p><p><strongx-text="show"></strong></p></div>
<divx-data="{ show: false }"class="text-center"><px-show="show">not working !</p><px-show="!show">It working !</p><p><strongx-text="show"></strong></p></div>
Example 2
If you want to show element one time at click.
<divx-data="{ show: false }"><buttonx-on:click="show = true">show</button><px-show="show">show Paragraph</p></div>
Do This ✅
If you want to show and hide then use = ! it react opposite value.
<divx-data="{ show: false }"><buttonx-on:click="show = !show">show</button><px-show="show">show Paragraph</p></div>
For much better Do This ✅
if you want show and hide with button value then do this.
<divx-data="{ show: false }"><buttonx-on:click="show = !show"x-text="!show ? 'Show' : 'Hide'">show</button><px-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)
For further actions, you may consider blocking this person and/orreporting abuse