Skip to content

Instantly share code, notes, and snippets.

@henrikvtcodes
Last active December 18, 2023 08:14
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save henrikvtcodes/feedaa564958f5d0b144f6b65c1fe52d to your computer and use it in GitHub Desktop.
Save henrikvtcodes/feedaa564958f5d0b144f6b65c1fe52d to your computer and use it in GitHub Desktop.
Two utilities that help with using `class-variance-authority`, Tailwind CSS, and `clsx`

Utilities for using Tailwind and CVA

Here are two utility functions created by merging the power of Joe Bell's class-variance-authority package, tailwind-merge, and clsx.

twcx

Combines tailwind-merge and clsx into a function that allows for conditional classnames without the worry of Tailwind style conflicts as the output is ran thru twMerge to get rid of duplicates.

twCVA

Takes in a cva instance and returns a function that extends cva's functionality with power of the aforementioned twcx function.

import clsx, { ClassValue } from 'clsx';
import { twMerge } from 'tailwind-merge';
export const twcx = (...inputs: ClassValue[]) => {
return twMerge(clsx(...inputs));
};
/**
*
* @param cvaInstance the cva function to use
* @returns a function that takes the variants and className and returns the merged classnames
*/
export const twCVA = <T extends (props: any) => string>(cvaFn: T) => {
return (variants?: Parameters<T>[0], ...classList: ClassValue[]) =>
twcx(cvaFn(variants), ...classList);
};
@CHE1RON
Copy link

CHE1RON commented Dec 18, 2023

Could you add an example how to use this? 🙏

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment