Last active
April 4, 2023 06:12
-
-
Save junchaw/7c68600198fa98c56af7703df83a2756 to your computer and use it in GitHub Desktop.
TailwindCSS class management with cva (Class Variance Authority) in a React component
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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