#1 Data Analytics Program in India
₹2,499₹1,499Enroll Now
3 min read
Question 30 of 38medium

What is tailwind-merge?

Merging Tailwind classes without conflicts.

What You'll Learn

  • Why tailwind-merge exists
  • How to use it
  • Common patterns

The Problem

code.txtJSX
// Without tailwind-merge
<div className={`p-4 ${className}`}>
// If className="p-2", result is "p-4 p-2" (conflict!)

The Solution

$ terminalBash
npm install tailwind-merge
code.txtJSX
import { twMerge } from 'tailwind-merge'

// Later classes win
twMerge('p-4 p-2')  // → 'p-2'
twMerge('px-4 py-2 p-6')  // → 'p-6'

Component Pattern

code.txtJSX
function Button({ className, children }) {
  return (
    <button className={twMerge(
      'px-4 py-2 bg-blue-500 text-white rounded',
      className
    )}>
      {children}
    </button>
  )
}

// Usage - override any defaults
<Button className="bg-red-500 px-8">
  Red with more padding
</Button>

With clsx/classnames

code.txtJSX
import { twMerge } from 'tailwind-merge'
import clsx from 'clsx'

// Combine both
const cn = (...inputs) => twMerge(clsx(inputs))

// Usage
cn('p-4', isActive && 'bg-blue-500', className)