gitmyhub

classnames

JavaScript ★ 18k updated 1d ago

A simple javascript utility for conditionally joining classNames together

A tiny JavaScript utility that builds CSS class name strings from conditions, pass strings, arrays, and objects and it returns only the class names whose conditions are true, eliminating messy string concatenation.

JavaScriptsetup: easycomplexity 1/5

classnames is a tiny JavaScript utility that helps you build CSS class name strings from multiple conditions. In web development, HTML elements get their visual styles applied through class names — strings like "btn btn-pressed btn-large" — and when your code needs to decide which classes apply based on application state, assembling that string gets messy fast.

The problem is straightforward: you might have a button that needs the class "btn" always, plus "btn-pressed" only when the user is clicking, plus "btn-over" only when the cursor is hovering, and you want to avoid writing long chains of if-statements to manually concatenate these strings.

classnames accepts any mix of strings, arrays, and objects, and combines them into a single class string. When you pass an object, keys whose values are truthy (meaning true or a non-empty value) get included; falsy values get excluded. For example, passing the object {btn: true, 'btn-pressed': isPressed} produces "btn btn-pressed" only when isPressed is true. Null, false, and undefined arguments are silently ignored, so you can safely pass optional values without extra checks.

The library is most commonly used with component-based JavaScript UI frameworks where components receive class names from parent components and need to merge them with their own internal conditional classes. It installs from npm with a single command and works in both Node.js server environments and directly in browsers. There are also variant builds for deduplicating repeated class names and for working with CSS Modules (a system where class names are locally scoped). The full README is longer than what was provided.

Where it fits