DEV Community

Gabriel Linassi
Gabriel Linassi

Posted on

A more stylish way to write conditional Tailwind classes

TLDR; Instead of writting like this:

  '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:

  '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, } = props
  return (
      className={clsx('rounded px-2 py-1', variantStyle[variant], className)}

export default Button
Enter fullscreen mode Exit fullscreen mode

Image description

Top comments (1)

armandsuiska profile image

Downside for this object mapping approach is that Rider tailwindcss ( don't show intellisense for available classes