It's Christmas, get a 30% OFF. Apply code XMAS at checkout.
Let’s create a dynamic tab component using Alpine.js and Tailwind CSS, but first…
Tabs streamline user interfaces and enhance web experiences in numerous ways:
Tabs not only make content more accessible and appealing but also ensure a smoother and more engaging user experience.
The first step is to create the HTML structure for the tabs and panels. and this is how it looks like:
<div
x-data="{ activeTab: 0 }"
>
<!-- Tab List -->
<ul
role="tablist">
<!-- Tab 1 -->
<li>
<button
@click="activeTab = 0"
:aria-selected="activeTab === 0"
:class="{ '...': activeTab === 0 }"
class="..."
role="tab">
<!-- Icon and Title for Tab 1 -->
<span>My Account</span>
</button>
</li>
<!-- Tab 2 -->
<li>
<button
@click="activeTab = 1"
:aria-selected="activeTab === 1"
:class="{ '...': activeTab === 1 }"
class="..."
role="tab">
<span>Billing</span>
</button>
</li>
</ul>
<!-- Panels -->
<div
role="tabpanels">
<!-- Panel 1 -->
<section
x-show="activeTab === 0"
role="tabpanel">
<!-- Content for Panel 1 -->
</section>
<!-- Panel 2 -->
<section
x-show="activeTab === 1"
role="tabpanel">
<!-- Content for Panel 2 -->
</section>
</div>
</div>
x-data
attribute is used to define the initial state of the component, in this case, the active tab is set to 0.role
attribute is set to tablist
to indicate that the list of tabs is a tablist.role
attribute is set to tabpanels
to indicate that the list of panels is a tabpanels.role
attribute is set to tabpanel
to indicate that each panel is a tabpanel.aria-selected
attribute is set to true
for the active tab and false
for the inactive tabs.class
attribute is set to ...
to indicate that the class should be dynamically generated based on the active tab.@click
attribute is used to handle the click event on the tabs and update the active tab state.x-show
attribute is used to show or hide the corresponding panel based on the active tab.You can customize the CSS classes and styles to match your design preferences. In this example, we’re using Tailwind CSS classes to style the tabs and panels. Hope you enjoyed the tutorial and learned how to create a tab component with Tailwind CSS and Alpine.js.
/Michael Andreuzza
Unlock all themes for $199 for forever! Includes lifetime updates, new
themes, unlimited projects, and support. No subscription needed.
— No subscription required!