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?
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))
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:
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With