A tiny utility for conditionally joining classNames together.
npm install @lickle/cn # or yarn add @lickle/cn or pnpm add @lickle/cn or jsr add @lickle/cn
This utility is similar to clx or classnames, with an additional tuple syntax [boolean, show if true, show if false]
.
Unlike those libraries, this provides two versions of the function:
- tcn: Returns a string literal type (useful for better IDE autocomplete and type inference).
- cn: Returns a string type
import { cn, tcn } from '@lickle/cn'
// Basic usage
cn('rounded-full', active && 'bg-blue')
// Conditional classes using objects
cn('bg-white', { 'border-blue': active })
// Tuple syntax for conditional rendering
cn([active, 'border-black', 'border-white'])
// Falsy values are ignored
cn(null, undefined, false, true)
// Type inference in action
const classes = tcn('bg-white', [active, 'border-blue', 'border-white'])
// Inferred type: "bg-white border-blue" | "bg-white border-white"
Enable classes autocompletion using cn
with Tailwind CSS.
Visual Studio Code
-
Install the "Tailwind CSS IntelliSense" Visual Studio Code extension
-
Add the following to your
settings.json
:
{
"tailwindCSS.experimental.classRegex": [
["cn\\(([^)]*)\\)", "(?:'|\"|`)([^']*)(?:'|\"|`)"],
["tcn\\(([^)]*)\\)", "(?:'|\"|`)([^']*)(?:'|\"|`)"]
]
}
MIT © Dan Beaven