Variants
Twux supports option and boolean variants.
- Option Variants: Select from a list of predefined options.
- Boolean Variants: Toggle a class on or off using a boolean prop.
Twux also supports default values for variant props.
Option Variants
Option variants are used to select from a list of predefined Tailwind classes.
The second argument to twux is an object that describes the variant props your
component supports.
import { twux } from "twux";
const VariantButton = twux(
"text-white rounded-md p-2",
{
color: {
primary: "bg-blue-500",
danger: "bg-red-500",
},
size: {
sm: "text-sm",
md: "text-base",
},
},
"button"
);Usage:
<VariantButton color="primary" size="sm">
Variant 1
</VariantButton><VariantButton color="danger" size="md">
Variant 1
</VariantButton>Each key under the variants object (style, size) becomes a prop on the resulting component, and each nested key (primary, danger, sm, md) maps to the Tailwind classes that should be applied when that value is selected.
Option Variants and Type Safety
Twux ensures required variant props are present and valid. If a required variant prop is missing or invalid, you will see a type error.
// Type error: The color prop is required and missing
<VariantButton size="md">
Click me
</MyButton>
// Type error: The color prop is invalid
<VariantButton size="md" color="invalid">
Click me
</MyButton>Boolean Variants
Use Boolean variants to toggle a class on or off using a boolean prop.
The second argument to twux is an object that describes the variant props your component supports.
const MyParagraph = twux(
"text-gray-800 leading-relaxed",
{
dazzle: "text-xl font-semibold italic text-purple-600",
},
"p"
);
export function BooleanVariantsExample() {
return (
<>
<MyParagraph>This paragraph uses the base styles.</MyParagraph>
<MyParagraph dazzle>Dazzling paragraph!</MyParagraph>
</>
);
}This paragraph uses the base styles.
Dazzling paragraph!
Default Values
You can add a third object argument to supply default values for your variants.
When a value isn’t provided for a variant, the default value is used.
const MyButton = twux(
"inline-flex items-center gap-2 rounded-md px-4 py-2 font-medium text-white transition-colors focus:outline-none focus:ring-2 focus:ring-offset-2",
{
style: {
primary: "bg-blue-500 hover:bg-blue-600 focus:ring-blue-500",
danger: "bg-red-500 hover:bg-red-600 focus:ring-red-500",
},
size: {
sm: "text-sm",
md: "text-base",
lg: "text-lg",
},
},
// Default values go here
{
style: "primary",
size: "md",
},
"button"
);With defaults in place you can omit a variant prop, and Twux will apply the fallback value and its classes automatically.
Default Boolean Variants
Combine boolean variants with the defaults object to turn a flag on by default.
const MyParagraph = twux(
"text-gray-800 leading-relaxed",
{
dazzle: "text-xl font-semibold italic text-purple-600",
},
{
dazzle: true,
},
"p"
);