cn

Utilities for combining classNames with Tailwind v4's improved class conflict resolution.

What Changed in Tailwind v4?

  • Simplified Configuration: No custom tailwind-merge configuration needed
  • Auto Conflict Resolution: Tailwind v4 handles most class conflicts automatically
  • CSS-First Approach: AlignUI colors are now defined in CSS using @theme

Installation

Install the following dependencies:

terminal
npm install clsx tailwind-merge

Create a utils/cn.ts file and paste the following code into it.

/utils/cn.ts
import clsx, { type ClassValue } from 'clsx';
import { twMerge } from 'tailwind-merge';
 
export { type ClassValue } from 'clsx';
 
/**
 * Utilizes `clsx` with `tailwind-merge`, use in cases of possible class conflicts.
 */
export function cn(...classes: ClassValue[]) {
  return twMerge(clsx(...classes));
}

IntelliSense setup (optional)

If you are using VSCode and the TailwindCSS IntelliSense Extension, you have to add the following to your .vscode/settings.json file to enable Intellisense features for cn and tv functions.

.vscode/settings.json
"tailwindCSS.experimental.classRegex": [
  ["([\"'`][^\"'`]*.*?[\"'`])", "[\"'`]([^\"'`]*).*?[\"'`]"]
]

Prettier setup (optional)

If you're using prettier-plugin-tailwindcss, you can include cn in the functions list to ensure it gets sorted as well.

prettier.config.mjs
const config = {
  // ...
  plugins: ['prettier-plugin-tailwindcss'],
  tailwindFunctions: ['cn'],
};
 
export default config;

Examples

cn

In this example, cn is used to merge Tailwind classes and conditionally apply styles based on the isActive prop. Tailwind v4's improved conflict resolution handles the class merging automatically.

/examples/cn-ext.ts
import { cn } from '@/utils/cn';
 
function MyComponent({
  className,
  isActive,
  ...rest
}: React.HTMLAttributes<HTMLDivElement> & {
  isActive?: boolean;
}) {
  return (
    <div
      className={cn(
        'text-text-strong-950 bg-bg-white-0 size-3',
        {
          'text-text-white-0 bg-bg-strong-950': isActive,
        },
        className,
      )}
      {...rest}
    />
  );
}
© 2024 AlignUI Design System. All rights reserved.