What is the proper way in Tailwind to toggle a UI state?

Viewed 603

I'm a complete Tailwind css newbie and am playing with it in a small project.

What is the idiomatic way to toggle the UI state of a tab? Here are a couple tabs taken straight from the Tailwind website:

      <nav class="-mb-px flex space-x-8" aria-label="Tabs">
        <a class="border-transparent text-gray-500 hover:text-gray-700 hover:border-gray-300 whitespace-nowrap py-4 px-1 border-b-2 font-medium text-sm">
          Tab 1
        </a>

        <a class="border-transparent text-gray-500 hover:text-gray-700 hover:border-gray-300 whitespace-nowrap py-4 px-1 border-b-2 font-medium text-sm">
          Tab 2
        </a>

        <a class="border-indigo-500 text-indigo-600 whitespace-nowrap py-4 px-1 border-b-2 font-medium text-sm">
          Tab 3
        </a>
      </nav>

As you can see, Tab 3 is the "selected" state. What if I want to change selection to Tab 1. I'd have to swap a bunch of the utility classes (border-indigo-500 into border-transparent, etc.).

With vanilla CSS, you might define a css class called .selected that would override a normal tab's css and toggle that class on the html element, but I don't think that's the idiomatic way that tailwind recommends here.

Sorry if this is a super newbie question. Thanks.

1 Answers

For this, you can maintain three variables. One that contains the selected tab value:

let selectedTab = "tab1" 

And the other classnames of an active and non-active tab. Something like this:

const active = "border-indigo-500 text-indigo-600 whitespace-nowrap py-4 px-1 border-b-2 font-medium text-sm"
const nonActive = "border-transparent text-gray-500 hover:text-gray-700 hover:border-gray-300 whitespace-nowrap py-4 px-1 border-b-2 font-medium text-sm"

Based on the click you change the value of the selected tab to its respective tab value and change the className of the HTML according to it.

Your HTML will look something like this

<nav class="-mb-px flex space-x-8" aria-label="Tabs">
  <a class={selectedTab === "tab1" ? active : nonActive}> Tab 1 </a>

  <a class={selectedTab === "tab2" ? active : nonActive}> Tab 2 </a>

  <a class={selectedTab === "tab3" ? active : nonActive}> Tab 3 </a>
</nav>
Related