Show/hide in Alpine.js with x-show
In Alpine.js the directive used to toggle visibility of an element is x-show
. Per the Alpine.js README, “x-show
toggles the display: none;
style on the element depending if the expression resolves to true
or false
”.
This means if we have a component with state { isShowing: false }
, we can use x-show="isShowing"
on an element to toggle its visibility.
If isShowing is false
, x-show
will set display: none
in the styles, which means the element will not show.
If isShowing is true
, x-show
will remove display: none
from the styles, which means the element will show.
A simple example to illustrate this is the following:
<div x-data="{ isShowing: false }">
<p x-show="isShowing">Shows when <code>isShowing</code> is true</p>
<p x-show="!isShowing">Shows when <code>isShowing</code> is false</p>
<p><code>isShowing: </code><code x-text="isShowing"></code></p>
</div>
Which displays the following in the browser:
The element with x-show="isShowing"
is hidden when isShowing
is false, the element with x-show="!isShowing"
is shown when isShowing
is false since !false
(not false
) evaluates to true
.
Since x-show
supports expressions (as do many Alpine.js directives), we can also pass boolean literals:
<div x-data="{}">
<p x-show="true">Always shown</p>
<p x-show="false">Always hidden</p>
</div>
In this case, we’ll have the following output
Another example of x-show
using expressions is logic operators, in this case, greater than/less than and equals operators.
<div x-data="{ count: 1 }">
<p x-show="count === 1">
Shown when count is 1 using <code>count === 1</code>
</p>
<p x-show="count >= 0">
Shown when count is greater than or equal to 0 using <code>count >= 0</code>
</p>
<p x-show="count === 2">
Shown when count is 2 using <code>count === 1</code>
</p>
<div><code>count: </code><code x-text="count"></code></div>
</div>
Which shows the following output
Similarly, any function that returns a boolean (eg. Array#includes()
) can be used in the expression for x-show
.
We’ve now seen how to toggle the visibility of elements based on expressions that return booleans.
You can find the examples for this post at Alpine.js Handbook Examples - 1.2 Show-Hide
That’s it for this post, you can check out the Alpine.js tag on Code with Hugo for more in-depth Alpine.js guides.
If you’re interested in Alpine.js, Subscribe to Alpine.js Weekly. A free, once–weekly email roundup of Alpine.js news and articles.
Photo by Avinash Kumar on Unsplash
Interested in Alpine.js?
Subscribe to Alpine.js Weekly. A free, once–weekly email roundup of Alpine.js news and articles