Combine tailwind-merge and clsx to conditionally set classes with a cn() utility function in a React + Tailwind environment
Install the tailwind-merge and clsx packages.
Define the cn()
function. In a file, perhaps src/lib/utils.ts
add:
import { type ClassValue, clsx } from "clsx";
import { twMerge } from "tailwind-merge";
export function cn(...inputs: ClassValue[]) {
return twMerge(clsx(inputs));
}
Some usage examples:
Dynamically change class based on variable value:
className={cn(`${isCollapsed ? "max-w-8" : "w-auto"}`)}
Or
className={cn(
form.formState.errors.email &&
"focus-visible:ring-red border-red-200 bg-red-100",
)}
Combine classes defined in the use with classes defined on the component (in this case the component takes className:string
as an argument and appends it to the applied class names while also dynamically changing the class based on the isCollapsed
variable):
className={cn(
`fixed left-0 right-0 top-0 z-[50] ${isCollapsed ? "md:w-14" : "md:w-80"}`,
className,
)}
Feedback?
Email us at enquiries@kinsa.cc.