Now that we've gone over how to build a component library in Create Tailwind Component Library, lets go over one way you can add variants to your components. Variants allow you to show different appearances based on props you pass. For example, you may want one Button variant to use the primary color and another use a shade red to show error or "danger" state. In this post I will introduce Tailwind Variants and show a basic implementation. I will link the documentation at the end of this post for further reading.
The power of Tailwind combined with a first-class variant API.
Tailwind Variants is developed by the team that works on NextUI. It was created to add the functionalities missing from CVA while they were migrating from Stitches to Tailwind. There is a comparison table to help determine if CVA or Tailwind Variants is right for your project.
In this example (from tailwind-variants) we are going to create a button with primary and danger variants. The base
prop will apply the styles to all the button variants. Then we added variants.color
. This means we have defined color as an available variant. To add a new variant to color, simply add a prop name within the color object and pass it the Tailwind CSS.
import { tv } from 'tailwind-variants';
// Create variants with tv
const button = tv({
base: 'font-semibold text-white text-sm py-1 px-4 rounded-full active:opacity-80',
variants: {
color: {
primary: 'bg-blue-500 hover:bg-blue-700',
danger: 'bg-red-500 hover:bg-red-700'
}
}
});
Now that we've created our variants, we can invoke the callback and pass the variants as props within the class
attribute.
const Button = ({ color = 'primary', text })=>{
return <button className={button({ color })}>{text}</button>
}
Checkout the rest of the documentation on Tailwind Variants.