Building React Components with Variants Using Tailwind CSS

Using Tailwind CSS is a great framework for quickly building rich user interfaces with it's extensive utility first classes, however, adding style variants to custom components can quickly become complex to manage without a good strategy.
In this article I'll be covering some strategies for building components with variants using Tailwind CSS, including:
- What are component variants?
- How to add variants
- Compound variants
- Creating reusable variants
- Strategies for good component composition
What are Tailwind CSS component variants?
Tailwind CSS has the concept of variants at the plugin level but component variants in this case are at the component level.
Component variants are React props with type-safe preset options that change a component's styles by managing what Tailwind CSS utility classes get applied based on the prop value.
Why are Tailwind CSS component variants important?
Having a good strategy to apply Tailwind CSS class variants will improve the following:
- Makes components easier to read without tons of logic to add or remove classes.
- Maintains a uniform consistency in naming and variant options.
- Type-safe variant options.
- Better overall component composition.
- Variants can be resusable for other components
Prerequisites
I'll assume that you have a React app with Tailwind CSS already configured. If not head over and get that set up first.
Required libraries
Also, you'll need to install some packages:
cva: class variance authority which is a lightweight, type-safe, CSS-in-TS library to extract and apply Tailwind CSS variant classes very easily.clsx: A library to conditionally apply classes and also used bycvainternally.tailwind-merge: Utility function to merge Tailwind CSS classes without potential style conflicts.
1npm i cva clsx tailwind-merge
Merging Tailwind CSS
When applying several Tailwind CSS utility classes it has become good practice to use a merge utility to avoid any style conflicts. The tailwind-merge utility library does this very efficiently.
We'll add a cn utility function which is short for className. You can rename to your preference. This function will do all of the merging for us using the tailwind-merge and clsx functions.
1import { type ClassValue, clsx } from "clsx";2import { twMerge } from "tailwind-merge";34export function cn(...inputs: ClassValue[]) {5 return twMerge(clsx(inputs))6}
Tailwind CSS Intellisense
Lastly, if you don't have a Tailwind CSS code intellisense extension, I highly recommend adding Tailwind CSS IntelliSense Visual Studio Code extension.
Adding the following regex lines to your Visual Studio Code settings.json will allow for Tailwind CSS intellisense for classes defined inside the cva() and cn() functions we'll be using.
1{2 "tailwindCSS.experimental.classRegex": [3 ["cva\\(([^)]*)\\)", "[\"'`]([^\"'`]*).*?[\"'`]"],4 ["cn\\(([^)]*)\\)", "(?:'|\"|`)([^']*)(?:'|\"|`)"]5 ],6}



