DEV Community

Gabriel Linassi
Gabriel Linassi

Posted on

4 1

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

Hostinger image

Get n8n VPS hosting 3x cheaper than a cloud solution

Get fast, easy, secure n8n VPS hosting from $4.99/mo at Hostinger. Automate any workflow using a pre-installed n8n application and no-code customization.

Start now

Top comments (2)

Collapse
 
armandsuiska profile image
Armands

Downside for this object mapping approach is that Rider tailwindcss (jetbrains.com/help/rider/Tailwind_...) don't show intellisense for available classes

Collapse
 
gabrielmlinassi profile image
Gabriel Linassi

This article is outdated. I recommend using tailwind-variants now or cva.

AWS Security LIVE!

Join us for AWS Security LIVE!

Discover the future of cloud security. Tune in live for trends, tips, and solutions from AWS and AWS Partners.

Learn More

👋 Kindness is contagious

Please leave a ❤️ or a friendly comment on this post if you found it helpful!

Okay