条件付きテールウインドクラスを書くよりスタイリッシュな方法


TLRこのように書く代わりに:
className={clsx(
  'rounded px-2 py-1',
  variant == 'contained' && 'bg-blue-500 text-white',
  variant == 'outlined' && 'border border-blue-500 text-blue-500'
)}
以下を好む
className={clsx(
  'rounded px-2 py-1',
  variantStyle[variant], className
)}
完全な実装
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