In this lesson, we create a set of tabs with Alpine JS, where only the content of the currently active tab is visible. To do this, we define an activeTab
state value with x-data. We then wire up our buttons to change the value of
activeTabon click, and use
x-showto determine if the tab content should be visible or not, based on the value of
activeTab`.
We also take control of the class
attribute with x-bind
, and we conditionally output an "active" class based on, you guessed it, the value of activeTab
.
Instructor: [0:00] Here we have three buttons and three blocks of text. We want to turn this into tabs and only show one text block at a time based on which button was clicked. Only one tab can be active at a time. Let's define a piece of state to represent that. In the wrapping element here, I'll do x-data= and define an activeTab state initially set to .
[0:23] In my three buttons, I will add an @click event, and set this activeTab to respective tab ids, , 1 and 2. Let's verify that it works with a pre tag with x-text="activeTab". Yep, we can see the value updating.
[0:42] Now, let's toggle the visibility of each text block. We'll use another Alpine.js directive, x-show, which lets us pass an expression that should resolve to true or false. For each, we'll want to check if the active tab value is equal to the tab id , 1 or 2. Here we go, we're now only showing the content for the tab that was clicked.
[1:05] Let's also change the styles of the tab that is currently active. Here's yet another Alpine.js directive, x-bind, which allows us to take control over the value of an attribute. In our case, the class attribute. Note that this directive has a shorthand syntax. X-bind lets you use a JavaScript expression to determine the value of an attribute, but in the case of the class attribute, it behaves a little bit differently.
[1:29] What it expects is an object where the key is a class name and the value a Boolean expression to determine if the class should be applied or not. In our case, we want the class active to be applied. We only want to apply it when activeTab is equal to the tab id, again , 1 or 2.
[1:48] We can now see our activeTab styled differently. Nice.