Skip to content

Go further with Compound Variants ​

Compound variants help you avoid deeply nested if-else statements in your codebase. They can also define conditions based on the variants or props you specify.

ts
import { compose, VariantProps } from "@busbud/tailwind-buddy";

type ComposeType = {
  "slots": ["root", "label"],
  variants: {
    variant: ["red", "blue"]
  },
  props: { 
    isDisabled: boolean,
  },
  screens: []
}

export const simpleVariants = compose<ComposeType>({
    slots: {
        "root": /** @tw */ "p-4",
        "label": "text-red-500"
    },
    variants: {
        variant: {
            "red": {
                root: "bg-red-500",
                label: "text-white"
            },
            "blue": "bg-blue-500"
        }
    },
    defaultVariants: {
        variant: "red"
    },
    compoundVariants: [  
      {  
        conditions: {  
          isDisabled: true,  
          // this can be also just one string value
          variant: ["blue", "red"]  
        },  
        // you can as for variants pass an Object of slots value as { root: "bg-purple"}
        classes: "bg-purple-500"
      }  
    ]  
})

// export type so we can use it in the component after
export type SimpleProps = VariantProps<ComposeType["variants"]> & ComposeType["props"];
ts
import { simpleVariants, SimpleProps } from "./Simple.variants.ts"

export const Simple: React.FC<SimpleProps> = (props) => {
  const { slots: { root, label } } = simpleVariants;
  return (
    <div className={root({ 
        variant: props.variant, 
        isDisabled: props.isDisabled || 100 > 0
    })}>
        <div className={label({
            variant: props.variant
        })}>
            Hello
        </div>
    </div>
  );
};