You often need to show or hide elements on your page with a condition. This is usually done by using JavaScript by changing the CSS styles of elements. Alpine JS offers x-show
directive to conditionally show or hide an element.
Using x-show
to Show or Hide an Element
Using x-show
is used to show or hide elements in the DOM. This actually adds style properties of display:none
or display:block
depending on the value. The following example illustrates how to show an element with a button click with x-show
.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 |
<div x-data="{showContactInformation:false}" x-cloak=""> <div class="flex justify-center"> <button @click="showContactInformation=true" class="mt-10 rounded-lg bg-blue-500 px-5 py-2 text-white" > Click to Show Content </button> </div> <div x-show="showContactInformation" class="mt-10 p-10"> <h1 class="text-center text-2xl font-bold">About Us</h1> <p> Lorem ipsum dolor sit amet consectetur, adipisicing elit. Molestias accusantium tenetur adipisci id? Corrupti laboriosam assumenda voluptates nesciunt sit beatae quas quis molestias maiores voluptatibus, iure reiciendis deleniti neque debitis. </p> </div> </div> |
Difference Between x-if
and x-show
You might ask, what’s the difference between x-if
and x-show
because you can hide an element with x-if
as well. The x-if
directive is useful in many other situations like adding to conditional classes or showing or hiding a modal. The x-show
directive is specifically designed to show or hide an element in the DOM like a div or a button.
Conclusion
You can hide or show an element with x-show
directive in Alpine JS. This directive removes or adds the element in the DOM tree depending on the condition. The x-show
comes in handy when you have a section that you want to show on a specific condition. Please read more on the official docs of Alpine JS.