DEV Community

Gabriel Linassi
Gabriel Linassi

Posted on

A more stylish way to write conditional Tailwind classes

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'
)}
Enter fullscreen mode Exit fullscreen mode

Prefer this:

className={clsx(
  'rounded px-2 py-1',
  variantStyle[variant], className
)}
Enter fullscreen mode Exit fullscreen mode

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
Enter fullscreen mode Exit fullscreen mode

Image description

Discussion (0)