Combining clsx and tailwind-merge for dynamic class lists in web applications

Created Updated
3 min read 414 words

In modern web development, creating dynamic class lists for elements is a common task, especially in Dynamic applications. Two popular libraries used for managing class names are clsx and tailwind-merge. clsx allows for conditional class rendering, while tailwind-merge simplifies the integration of Tailwind CSS classes into components. Combining these two libraries can streamline the process of managing dynamic class lists in your projects.

Installing the Libraries

Before we dive into the implementation, make sure you have both clsx and tailwind-merge installed in your project. You can install them using npm or yarn:

npm install clsx tailwind-merge
# or
yarn add clsx tailwind-merge
# or
pnpm install clsx tailwind-merge

Basic Usage of clsx and tailwind-merge

First, let’s briefly discuss the basic usage of clsx and tailwind-merge.

clsx

clsx is used to conditionally concatenate class names based on the given arguments. Here’s a simple example:

import clsx from 'clsx';

const Button = ({ primary }: {primary: boolean}) => {
  const classes = clsx('button', { 'button-primary': primary });
  return <button className={classes}>Click me</button>;
};

twMerge

twMerge simplifies the integration of Tailwind CSS classes into your components removing any duplicate or overlapping classes. Here’s how you can use it:

import { twMerge } from 'tailwind-merge';

const App = () => {
  const buttonStyles = twMerge('bg-blue-500', 'text-white', 'bg-red-500', 'p-2');
  // will only have `bg-blue-500`, `text-white` & `p-2`
  return <button className={buttonStyles}>Click me</button>;
};

Combining clsx and tailwind-merge

To combine clsx and tailwind-merge for managing dynamic class lists, you can create a utility function that merges the class names generated by both libraries. Here’s how you can do it:

import { twMerge } from "tailwind-merge";
import clsx, { type ClassValue } from "clsx";

export const cn = (...classes: ClassValue[]) => twMerge(clsx(classes));

const App = ({ primary }) => {
  const buttonClasses = cn('button', ['bg-blue-500', 'text-white', 'p-2'], { 'button-primary': primary });
  return <button className={buttonClasses}>Click me</button>;
};

In this example, the cn function takes an array of class names or arrays of Tailwind CSS classes and conditionally merges them using clsx and twMerge. This allows you to create dynamic class lists with both static and Tailwind CSS classes in a concise and readable way.

Conclusion

Combining clsx and twMerge can be a powerful approach for managing dynamic class lists in your applications. By leveraging the strengths of both libraries, you can create flexible and maintainable components with ease. Experiment with different configurations to find the best approach for your projects.

YouTube References

Add comment below...

Please refresh the page if commenting system is not visible.