alpine js x-show example

In this Alpine js tutorial we will see x-show . x-show is one of the most useful and powerful directives in Alpine js. It provides show and hide DOM elements. x-show by default display: none; style on depending if the expression resolves to true or false. if true then it will show elements if false then it will hide the elements let see some example.

Example 1

it will not show .because show is false which mean it style is 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>
Alpine js x-show v1

Alpine js x-show v1


Do This ✅

<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>
Alpine js x-show v2

Alpine js x-show v2


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 many place like eg.

Show and hide Model

Drop down and Toggle

In FAQ Section

Responsive Navbar


Related Posts 

👉 Alpine js x-data Tutorial by Example

👉 Build Simple Count App Using Alpine js with Tailwind CSS

👉 Alpine js hide show Password with Tailwind CSS Example