0
0
Tailwindmarkup~30 mins

Conditional classes with clsx and twMerge in Tailwind - Mini Project: Build & Apply

Choose your learning style9 modes available
Conditional classes with clsx and twMerge
📖 Scenario: You are building a simple button component for a website. The button should look different when it is active or disabled. You will use Tailwind CSS classes to style the button. To manage the classes easily, you will use the clsx library to add classes conditionally and twMerge to combine classes without duplicates.
🎯 Goal: Create a button with conditional Tailwind CSS classes using clsx and twMerge. The button should have a base style, an active style when isActive is true, and a disabled style when isDisabled is true. Use clsx to add classes based on these conditions and twMerge to merge them properly.
📋 What You'll Learn
Create a base set of Tailwind CSS classes for the button.
Create two boolean variables: isActive and isDisabled.
Use clsx to conditionally add classes based on isActive and isDisabled.
Use twMerge to merge the classes into one string.
Render a button element with the merged class string.
💡 Why This Matters
🌍 Real World
Buttons with different states are everywhere on websites. Using clsx and twMerge helps keep the code clean and easy to manage when styles change based on state.
💼 Career
Understanding how to conditionally apply Tailwind CSS classes with clsx and twMerge is a valuable skill for frontend developers working with React and Tailwind CSS.
Progress0 / 4 steps
1
Set up base button classes
Create a constant called baseClasses and set it to the string "px-4 py-2 rounded font-semibold text-white" which will be the base Tailwind CSS classes for the button.
Tailwind
Need a hint?

Think of the base button style as the basic look that all buttons share.

2
Add boolean variables for state
Create two constants: isActive set to true and isDisabled set to false. These will control the button's state.
Tailwind
Need a hint?

Use const to create these boolean variables exactly as named.

3
Use clsx to add conditional classes
Import clsx and create a constant called conditionalClasses that uses clsx to add "bg-blue-500" if isActive is true, and "bg-gray-400 cursor-not-allowed" if isDisabled is true.
Tailwind
Need a hint?

Use an object inside clsx where keys are class strings and values are conditions.

4
Merge classes with twMerge and render button
Import twMerge from tailwind-merge. Create a constant called finalClasses that merges baseClasses and conditionalClasses using twMerge. Then write a JSX <button> element with className set to finalClasses and text content Click me.
Tailwind
Need a hint?

Use twMerge to combine the base and conditional classes into one string without duplicates. Then use that string in the button's className.