Skip to content

Instantly share code, notes, and snippets.

@junchaw
Last active April 4, 2023 06:12
Show Gist options
  • Save junchaw/7c68600198fa98c56af7703df83a2756 to your computer and use it in GitHub Desktop.
Save junchaw/7c68600198fa98c56af7703df83a2756 to your computer and use it in GitHub Desktop.
TailwindCSS class management with cva (Class Variance Authority) in a React component
import React from "react";
import classNames from "classnames";
import {cva, VariantProps} from "cva";
export const badge = cva(["inline-fcc", "rounded-full", "shadow"], {
variants: {
size: {
responsiveXs: [
"px-2",
"py-[.125rem]",
"text-xs",
"min-w-[1.25rem]",
],
responsiveSm: [
"px-2",
"py-[.125rem]",
"text-xs", "sm:text-sm",
"min-w-[1.25rem]", "sm:min-w-[1.5rem]",
],
responsiveMd: [
"px-2",
"py-[.125rem]",
"text-sm", "sm:text-base",
"min-w-[1.5rem]", "sm:min-w-[1.75rem]",
],
},
theme: {
primary: ["bg-primary-500", "text-gray-100"],
secondary: ["bg-gray-500", "text-gray-100"],
},
hoverable: {
"true": ["cursor-pointer"],
"false": [],
},
},
compoundVariants: [
{
theme: "primary",
hoverable: true,
className: ["hover:bg-primary-400", "hover:text-white"],
},
{
theme: "secondary",
hoverable: true,
className: ["hover:bg-gray-300", "hover:text-white"],
},
],
defaultVariants: {
size: "responsiveMd",
theme: "primary",
hoverable: false,
},
});
export type badgeVariants = VariantProps<typeof badge>;
export interface BadgeProps extends React.ComponentProps<"span"> {
variants?: badgeVariants,
}
export const Badge: React.FC<BadgeProps> = (
{
variants,
...props
},
) => {
if (props.onClick) {
if (!variants) variants = {}
variants.hoverable = variants.hoverable ?? true
}
props.className = classNames(
badge(variants),
props.className,
)
return <span {...props}/>
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment