Mastering Tailwind CSS: Overcome Styling Conflicts with Tailwind Merge and clsx

Sheraz ManzoorSheraz Manzoor
3 min read

People has been asking me to write something on some soft topics for beginners in my email, as I write mostly for Mid-level or senior. So, here is a new article for you beginners, specially for UI Developers ๐Ÿ˜.

Today, let's explore the common challenges developers face when working with Tailwind CSS and how to overcome them using the powerful combination of Tailwind Merge and clsx.

What's the problem?

When using Tailwind CSS, you often want to pass custom class names to your components, just like you would with a native HTML element, which allows you to style your components dynamically and override the default styles. However, this can lead to conflicts when the custom class names clash with the base Tailwind classes.

The problem with Tailwind is these conflicts are not predictable. You don't know the outcome really. It doesn't matter if you put this at the front of the class list or at the end, in both cases when you have a conflict, you don't really get the result that you expect.

The default behavior of Tailwind doesn't always align with our intuition, where we expect the last class to take precedence in case of a conflict.

Introducing Tailwind Merge

The finest solution to this tricky problem is a utility function called Tailwind Merge. This function intelligently merges conflicting Tailwind classes. It makes sure that the last class wins, which aligns with our expectations.

import { twMerge } from 'tailwind-merge';

const containerClasses = twMerge(
  'bg-blue-500 text-white px-4 py-2 rounded',
  'bg-red-500'
);

In example above, the twMerge function takes the base Tailwind classes and the custom class name as arguments, and returns the merged result. This way, the bg-re-500 class will override the bg-blue-500 class, as expected.

Handling Conditional Classes

Another common scenario is when you need to apply different classes based on a condition, such as a component's state. Tailwind Merge makes this easy to manage as well:

const buttonClasses = twMerge(
  'bg-blue-500 text-white px-4 py-2 rounded',
  'bg-green-500',
  isLoading && 'bg-gray-500'
);

In this case, if the isLoading variable is true, the bg-gray-500 class will be added to the final class string.

Introducing clsx

While Tailwind Merge solves the problem of conflicting classes, some developers prefer to use an object-based syntax for conditional classes. This is where the clsx library comes in handy.

import clsx from 'clsx';

const buttonClasses = twMerge(
  clsx({
    'bg-blue-500 cursor-not-allowed': !loading,
    'bg-gray-500 cursor-pointer': loading,
  }),
  'text-white px-4 py-2 rounded'
);

By using clsx, you can now define your conditional classes in an object-based format, which some developers find more intuitive.

Combining the powers of Tailwind Merge and clsx

To get the best of both worlds, you can combine Tailwind Merge and clsx using a custom utility function:

import { twMerge } from 'tailwind-merge';
import clsx from 'clsx';

export const cn = (...inputs: ClassValue[]) => {
  return twMerge(clsx(inputs));
};

This cn (short for "class names") function first passes the input classes through clsx, which handles the object-based conditional classes, and then passes the result to Tailwind Merge to resolve any conflicts.

Now, you can use this cn function in your components with both syntaxes:

const buttonClasses = cn(
  {
    'bg-blue-500': !pending,
    'bg-gray-500': pending,
  },
  'text-white px-4 py-2 rounded'
);

OR

const buttonClasses = cn(
 'text-white px-4 py-2 rounded', pending ? 'bg-blue-500' : 'bg-gray-500' 
);

This approach allows you to leverage the strengths of both Tailwind Merge and clsx together, providing a flexible and intuitive way to manage your component styles.

Conclusion

In conclusion, understanding and mastering the use of Tailwind Merge and clsx can greatly improve your experience when working with Tailwind CSS. By combining these tools, you can effectively manage class conflicts, conditional styles, and create reusable, well-structured components.

0
Subscribe to my newsletter

Read articles from Sheraz Manzoor directly inside your inbox. Subscribe to the newsletter, and don't miss out.

Written by

Sheraz Manzoor
Sheraz Manzoor

I am an experienced Frontend Developer currently working at Infinity Devs as a MERN Stack Developer. With a deep passion for creating intuitive and dynamic web applications, I specialize in technologies like React, Next.js, Typescript, zod, SaaS and Tailwind CSS. I pride myself on delivering clean, efficient, and responsive designs that not only meet but exceed client expectations. In my career, I have worked on everything from tiny websites for small businesses to complete custom web applications. With such a strong understanding of client needs, I utilize my own technical capabilities to create new solutions. By making my user experiences better or performance faster Key Skills: -Frontend Technologies: React, Next.js, HTML, CSS, JavaScript, Tailwind CSS -Version Control: Git, GitHub -Responsive Design: Mobile-first development, cross-browser compatibility -Collaboration: Excellent communication skills, experience in agile environments Professional Approach: -Shared Ownership: I believe in collaborative effort and shared responsibility to ensure the success of every project. -Rapid Execution: Efficiently managing time and resources to deliver quality work promptly -Show and Tell: Regular updates and transparency with clients to ensure alignment and satisfaction -Bias for Action: Prioritizing proactive measures to tackle challenges head-on -Systematic Approach: Methodical planning and execution to maintain high standards -Design Thinking: Emphasizing empathy and creativity to solve complex problems and deliver user-centric solutions Interests: When Iโ€™m not coding, you can find me exploring the latest in tech, reading about advancements in AI, or enjoying a good book. I also have a keen interest in photography and love capturing moments in nature.