Effortlessly creates and merges className strings without style conflicts using clsx
and tailwind-merge
.
Using npm:
npm i merge-class
Using pnpm:
pnpm add merge-class
Using yarn:
yarn add merge-class
Import mc
from merge-class
:
import { mc } from 'merge-class';
const className = mc('bg-red-500', 'hover:bg-red-600', 'active:bg-red-700');
console.log(className); // output: 'bg-red-500 hover:bg-red-600 active:bg-red-700'
The mc
(merge class) function is designed to combine class names into a single string, handling various cases such as conditional classes, undefined/null values, duplicates, arrays, nested arrays, and objects with boolean values. It also prioritizes Tailwind utility classes correctly.
-
Description: Should combine class names into a single string.
-
Test:
expect(mc('font-bold', 'w-4')).toBe('font-bold w-4');
-
Description: Should handle conditional classes correctly.
-
Test:
const condition = true; expect(mc('font-bold', condition && 'w-4')).toBe('font-bold w-4');
-
Description: Should eliminate undefined and null values.
-
Test:
expect(mc('font-bold', undefined, 'w-4', null)).toBe('font-bold w-4');
-
Description: Should merge duplicate classes and prioritize Tailwind utility classes.
-
Test:
expect(mc('p-4', 'p-2')).toBe('p-2');
-
Description: Should handle arrays of classes.
-
Test:
expect(mc(['font-bold', 'w-4'], ['px-2'])).toBe('font-bold w-4 px-2');
-
Description: Should handle nested arrays of classes.
-
Test:
expect(mc(['font-bold', ['w-4', 'px-2']])).toBe('font-bold w-4 px-2');
-
Description: Should process objects with boolean values.
-
Test:
expect(mc({ 'font-bold': true, 'w-4': false, 'px-2': true })).toBe('font-bold px-2');
-
Description: Should handle a mix of types.
-
Test:
const condition = false; expect(mc('font-bold', ['w-4', { 'px-2': true, 'h-5': condition }])).toBe('font-bold w-4 px-2');
-
Description: Should prioritize correctly with Tailwind utilities.
-
Test:
expect(mc('text-red-500', 'text-blue-500')).toBe('text-blue-500');