patterncsstailwindMajor
tailwind-merge (twMerge) to resolve conflicting Tailwind class strings
Viewed 0 times
tailwind-merge v2+
tailwind-mergetwMergeclass conflictclassName propoverridecomponent
Problem
A component accepts a
className prop that overrides default styles. When both the component default and the override target the same CSS property (e.g., p-4 and p-8), both classes end up in the DOM and the winner depends on stylesheet order — not the intended prop.Solution
Use
tailwind-merge to intelligently merge class strings, with later values winning:npm install tailwind-mergeimport { twMerge } from 'tailwind-merge';
function Button({ className, children }) {
return (
<button className={twMerge('px-4 py-2 bg-blue-600 text-white rounded', className)}>
{children}
</button>
);
}
// Consumer
<Button className="bg-red-600 px-8">Danger</Button>
// Result: 'py-2 text-white rounded bg-red-600 px-8'
// bg-blue-600 and px-4 are correctly removedWhy
Standard string concatenation (
cn(a, b)) cannot know that p-4 and p-8 conflict — both end up in the class list. twMerge has a built-in knowledge of which Tailwind utilities override each other and removes the losing class.Gotchas
- twMerge only knows about standard Tailwind classes. Custom arbitrary values or non-standard prefixes may not be resolved correctly without configuration.
- Use twMerge.extend to configure custom class groups if your theme adds utilities that conflict with each other.
- Combine with clsx for conditional class logic: twMerge(clsx(...)) is the canonical pattern.
Context
When building reusable components that accept a className prop for style customization.
Revisions (0)
No revisions yet.