We use conditional classes to change styles based on conditions. clsx helps combine class names easily. twMerge cleans up duplicate Tailwind classes so styles don't conflict.
Conditional classes with clsx and twMerge in Tailwind
import clsx from 'clsx'; import { twMerge } from 'tailwind-merge'; const className = twMerge(clsx( 'base-class', condition && 'conditional-class', anotherCondition ? 'class-true' : 'class-false' ));
clsx combines class names and ignores false or null values.
twMerge merges Tailwind classes and removes duplicates or conflicts.
text-blue-500 only if isActive is true.clsx('text-center', isActive && 'text-blue-500')
bg-blue-500 because twMerge keeps the last conflicting class.twMerge('bg-red-500', 'bg-blue-500')
isLarge, and background if isPrimary is true.twMerge(clsx('p-4', isLarge ? 'text-lg' : 'text-sm', isPrimary && 'bg-green-500'))
This example shows a button that changes style and text when clicked. It uses clsx to add classes conditionally and twMerge to merge Tailwind classes without conflicts. The button background changes from blue to green when active, and the text color changes accordingly.
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8" /> <meta name="viewport" content="width=device-width, initial-scale=1" /> <title>Conditional Classes Example</title> <script src="https://cdn.tailwindcss.com"></script> <script type="module"> import { twMerge } from 'https://cdn.skypack.dev/tailwind-merge'; import clsx from 'https://cdn.skypack.dev/clsx'; window.addEventListener('DOMContentLoaded', () => { const button = document.getElementById('myButton'); let isActive = false; function updateButton() { const className = twMerge(clsx( 'px-6 py-3 rounded font-semibold transition-colors', 'bg-blue-500 text-white', isActive && 'bg-green-500 text-black', !isActive && 'hover:bg-blue-700' )); button.className = className; button.textContent = isActive ? 'Active' : 'Inactive'; button.setAttribute('aria-pressed', isActive.toString()); } button.addEventListener('click', () => { isActive = !isActive; updateButton(); }); updateButton(); }); </script> </head> <body class="flex items-center justify-center min-h-screen bg-gray-100"> <button id="myButton" aria-pressed="false" aria-label="Toggle active state"></button> </body> </html>
Always use twMerge after clsx to avoid conflicting Tailwind classes.
Use semantic HTML and ARIA attributes for accessibility, like aria-pressed on toggle buttons.
Test your styles in different screen sizes to ensure responsiveness.
clsx helps combine class names easily and conditionally.
twMerge cleans up conflicting Tailwind classes to keep styles correct.
Use them together to write clean, dynamic, and conflict-free Tailwind CSS classes.
Practice
clsx in a Tailwind CSS project?Solution
Step 1: Understand clsx functionality
clsx is a utility that helps combine class names conditionally, making it easier to apply classes based on logic.Step 2: Compare options
Only To conditionally combine multiple class names into one string correctly describes clsx's purpose. Other options describe unrelated tasks.Final Answer:
To conditionally combine multiple class names into one string -> Option AQuick Check:
clsx combines classes conditionally = C [OK]
- Thinking clsx generates CSS classes
- Confusing clsx with CSS minifiers
- Assuming clsx replaces Tailwind CSS
clsx to conditionally add the class bg-blue-500 only when isActive is true?Solution
Step 1: Recall clsx conditional syntax
clsx accepts an object where keys are class names and values are booleans to include or exclude classes.Step 2: Analyze each option
clsx({ 'bg-blue-500': isActive }) uses the correct object syntax. Options B and C misuse logical operators, and D has invalid syntax.Final Answer:
clsx({ 'bg-blue-500': isActive }) -> Option BQuick Check:
clsx uses object with class:condition = A [OK]
- Using logical operators inside clsx incorrectly
- Missing quotes around class names
- Writing invalid object syntax
import clsx from 'clsx';
import { twMerge } from 'tailwind-merge';
const isPrimary = true;
const isDisabled = false;
const buttonClass = twMerge(clsx('px-4 py-2', {
'bg-blue-500': isPrimary,
'bg-gray-400': !isPrimary,
'opacity-50 cursor-not-allowed': isDisabled
}));
console.log(buttonClass);What will be printed in the console?
Solution
Step 1: Evaluate clsx conditions
isPrimary is true, so 'bg-blue-500' is included; !isPrimary is false, so 'bg-gray-400' is excluded; isDisabled is false, so 'opacity-50 cursor-not-allowed' is excluded.Step 2: Apply twMerge
twMerge cleans conflicting classes but here only 'bg-blue-500' is present, so no conflicts to resolve.Final Answer:
"px-4 py-2 bg-blue-500" -> Option AQuick Check:
clsx + twMerge output = "px-4 py-2 bg-blue-500" [OK]
- Including classes with false conditions
- Ignoring twMerge effect on conflicting classes
- Mixing up true/false conditions
clsx and twMerge:const isActive = true;
const classes = twMerge(clsx('text-white', {
'bg-red-500': isActive,
'bg-green-500' isActive === false
}));
console.log(classes);Solution
Step 1: Check object syntax inside clsx
Inside the object, properties must be separated by commas. The line 'bg-green-500' isActive === false lacks a comma after the first property.Step 2: Verify other parts
twMerge usage is correct assuming import exists, clsx accepts objects, and isActive is defined.Final Answer:
Missing comma between object properties inside clsx -> Option DQuick Check:
Object properties need commas = D [OK]
- Forgetting commas between object keys
- Assuming clsx can't take objects
- Ignoring variable definitions
bg-red-500 when error is true, bg-green-500 when success is true, and bg-gray-300 otherwise. Using clsx and twMerge, which code correctly applies these classes without conflicts?Solution
Step 1: Understand class conflicts
Only one background color class should be applied at a time to avoid conflicts.Step 2: Analyze each option
twMerge(clsx('px-4 py-2', { 'bg-red-500': error, 'bg-green-500': success, 'bg-gray-300': !error && !success })) uses clsx with multiple conditional classes that can conflict; twMerge will merge but logic is less clear. twMerge(clsx('px-4 py-2', error ? 'bg-red-500' : success ? 'bg-green-500' : 'bg-gray-300')) uses nested ternary to pick exactly one class, then twMerge cleans up. clsx(twMerge('px-4 py-2'), { 'bg-red-500': error, 'bg-green-500': success, 'bg-gray-300': !error && !success }) misuses clsx and twMerge order. clsx('px-4 py-2', error && 'bg-red-500', success && 'bg-green-500', !error && !success && 'bg-gray-300') uses clsx but may add multiple bg classes simultaneously.Step 3: Choose best practice
twMerge(clsx('px-4 py-2', error ? 'bg-red-500' : success ? 'bg-green-500' : 'bg-gray-300')) cleanly selects one bg class and uses twMerge properly.Final Answer:
twMerge(clsx('px-4 py-2', error ? 'bg-red-500' : success ? 'bg-green-500' : 'bg-gray-300')) -> Option CQuick Check:
Use ternary for exclusive classes + twMerge = B [OK]
- Applying multiple conflicting bg classes at once
- Wrong order of clsx and twMerge calls
- Not ensuring only one bg class is active
Ready to prove it?
Pass the test and this pattern moves unknown
