The cnx function is a utility to dynamically combine string class names based on various input types, such as strings, numbers, objects, arrays, or functions.
This function combines various input types and simplifies complex management by producing clean and valid strings.
Useful for dynamically managing string classes in JavaScript or TypeScript applications.
function cnx(...inputs: cnxValues[]): string;
// allows receiving Arrays, Objects and Functions
cnx(['', baz, (foo as string) !== 'foo' && bar], { '': !props }, '', () => ({ '' }), undefined, [{ '' }, () => ({ '' })]);
Initialization: An empty array (classes) is used to store valid strings.
Input Iteration:
Each item in the ...inputs
parameter (spread operator) is processed with the following logic:
cnx(...input)
to support nested structures.true
), the key (class name) is added to the array.cnx("hello", "world");
// Output: "hello world"
cnx(() => "there", "dynamic");
// Output: "there dynamic"
cnx(["extra", 0, false, "bar"]);
// Output: "extra bar"
cnx(Boolean, Object, undefined, null, "", 0, NaN);
// Output: ""
cnx("hello", true && "foo", false && "bar");
// Output: "hello foo"
cnx(["foo"], ["", 0, false, "bar"], [["baz", [["hello"], "there"]]]);
// Output: "foo bar baz hello there"
cnx("foo", [1 && "bar", { baz: false, bat: null }, ["hello", ["world"]]], "cya");
// Output: "foo bar hello world cya"
cnx("foo", { primary: true, disabled: false }, ["extra", null, undefined], () => "dynamic");
// Output: "foo primary extra dynamic"
cnx([{ color: "red", fontSize: "16px" }, () => ({ backgroundColor: "blue" }), undefined, [{ margin: "10px" }, () => ({ padding: "5px" })]]);
// Output: "color fontSize backgroundColor margin padding"
If you are using the vscode editor, enable autocomplete for the tailwindcss
class using the following command:
Tailwind CSS IntelliSense
Visual Studio Code extensionsettings.json
:"tailwindCSS.experimental.classRegex": [
["cnx\\(([^)]*)\\)", "(?:'|\"|`)([^']*)(?:'|\"|`)"],
["cn\\(([^)]*)\\)", "(?:'|\"|`)([^']*)(?:'|\"|`)"],
["merge\\(([^)]*)\\)", "(?:'|\"|`)([^']*)(?:'|\"|`)"],
],
{
"extends": ["prettier", "plugin:tailwindcss/recommended"],
"plugins": ["tailwindcss"],
"ignorePatterns": [],
"rules": {},
"settings": {
"tailwindcss": {
"callees": ["cn", "merge", "twMerge"],
"config": "tailwind.config.ts"
}
},
"overrides": []
}
Merge with tailwind-merge
import { cnx, type cnxValues } from "cretex";
import { twMerge } from "tailwind-merge";
function cn(...inputs: cnxValues[]) {
return twMerge(cnx(...inputs));
}
import { merge } from "cretex";
<div className={merge("bg-black/60 dark:bg-white/60 font-medium border", { "font-extrabold border-0": true })} />;