classes

Normalize strings, booleans, null and undefined into a valid React className string

1 min read

views

New kid on the block!

Heads up: there is a new utility package called mxcn that does pretty much the same thing as below. I'd recommend you use this package instead of the code below 😛.

Implementation

Add multiple classes that can also be type boolean, null and undefined.

src/util/classes.ts
export function classes(...arr: (string | boolean | null | undefined)[]): string {
  return arr.filter(Boolean).join(" ");
}
tsx

Usage

<div className={classes("myClass", isTrue && "anotherClass")}>Hello world!</div>
tsx