TLDR; Instead of writting like this:
className={clsx(
'rounded px-2 py-1',
variant == 'contained' && 'bg-blue-500 text-white',
variant == 'outlined' && 'border border-blue-500 text-blue-500'
)}
Prefer this:
className={clsx(
'rounded px-2 py-1',
variantStyle[variant], className
)}
Full implementation:
import clsx from 'clsx'
import { ButtonHTMLAttributes, FC } from 'react'
type Variants = 'outlined' | 'contained'
type ButtonProps = {
variant: Variants
} & ButtonHTMLAttributes<HTMLButtonElement>
const variantStyle: { [key in Variants]: string } = {
contained: 'bg-blue-500 text-white',
outlined: 'border border-blue-500 text-blue-500',
}
const Button: FC<ButtonProps> = (props) => {
const { children, variant, className, ...rest } = props
return (
<button
className={clsx('rounded px-2 py-1', variantStyle[variant], className)}
{...rest}
>
{children}
</button>
)
}
export default Button
Top comments (2)
Downside for this object mapping approach is that Rider tailwindcss (jetbrains.com/help/rider/Tailwind_...) don't show intellisense for available classes
This article is outdated. I recommend using tailwind-variants now or cva.