Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to properly join tailwind css classes using clsx?

I am trying to join tailwind classes and apply them to a button using clsx. One class is applied by default 'rounded-none' and the other one is passed in as a prop

const Button = ({
  children, ...props
}): JSX.Element => {

  return (
    <ADButton
      className={clsx('rounded-none', props.className)}
      {...props}
    >
      {children}
    </ADButton>
  );
};

Let's say I have added padding-top: 0px; to the button like shown below

<Button
  color="primary"
  className="pt-0"
>
  {t('btn.add')}
</Button>

The joined className should look like 'rounded-none pt-0'. If no className prop is passed, then just apply ‘rounded-none’

The problem am having right now is ‘rounded-none’ only gets applied to buttons without className prop. On buttons with className prop, only className prop gets applied but not ‘rounded-none’. How can I fix this so that both classes are joined and applied to the button?

like image 545
frre tyy Avatar asked Jan 20 '26 18:01

frre tyy


2 Answers

You could use a merge of clsx and twMerge twMerge to efficiently merge Tailwind CSS classes in JS without style conflict. Be carefull to dont override your previous classes

import clsx, { ClassValue } from 'clsx'
import { twMerge } from 'tailwind-merge'
export const cn = (...classes: ClassValue[]) => twMerge(clsx(...classes))
like image 107
Daher Avatar answered Jan 23 '26 10:01

Daher


You can combine both clsx and twMerge

Utility Function /lib/utils.ts

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

Use it as page.tsx


import { cn } from "@/lib/utils";
export default function Component(){
   return <div className={cn(
              "bg-black font-sans",
              "bg-white h-full", 
               {
                 "px-5":pending, // if pending is true apply padding
               }
           )}
         />
}

For explanation refer:

  • https://stackoverflow.com/a/76660733/13431819
  • cn() - Every Tailwind Coder Needs It (clsx + twMerge)
like image 37
krishnaacharyaa Avatar answered Jan 23 '26 11:01

krishnaacharyaa