dilkhush-raj
Code snippets

cn utility function

A utility function for merging Tailwind classes.

Introduction

The cn utility function is a simple implementation of the clsx and twMerge functions from the clsx and tailwind-merge packages. It allows you to merge Tailwind classes in a type-safe way.

Installation

To use the cn utility function, you need to install the clsx and tailwind-merge packages:

npm install clsx tailwind-merge

Code

/src/utils/cn.ts or /src/lib/utils.tsx

import { clsx, type ClassValue } from "clsx";
import { twMerge } from "tailwind-merge";
 
export function cn(...inputs: ClassValue[]) {
    return twMerge(clsx(inputs));
}

Usage

Here's an example of how to use the cn utility function:

import { cn } from "@/utils/cn";
 
const baseClass = "bg-blue-500 text-white";
const activeClass = "bg-red-500 text-white";
 
function Button() {
    const [isActive, setIsActive] = useState(false);
 
    const classes = cn(baseClass, isActive ? activeClass : "bg-gray-200");
 
    return (
        <button className={classes} onClick={() => setIsActive(!isActive)}>
            Click me
        </button>
    );
}

In this example, the cn function is used to create a class name based on the baseClass and activeClass variables. The isActive state variable is used to conditionally apply the activeClass to the class name.

On this page