Conditionally apply CSS classes in a React component based on state without writing messy ternary chains.
Merge className props passed in from a parent with a component's own internal conditional classes.
Build dynamic class strings for UI elements like buttons that have multiple visual states such as active or disabled.
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.
← jedwatson on gitmyhub — every repo by this author, as a profile.
Verify against the repo before relying on details.