A simple javascript utility for conditionally joining classNames together
Installations
npm install classnames
Developer Guide
Typescript
Yes
Module System
CommonJS, ESM
Node Version
20.10.0
NPM Version
10.2.3
Score
99.7
Supply Chain
99.5
Quality
81.2
Maintenance
100
Vulnerability
100
License
Releases
Unable to fetch releases
Contributors
Languages
JavaScript (81.92%)
TypeScript (16.81%)
HTML (1.28%)
Developer
JedWatson
Download Statistics
Total Downloads
2,771,307,849
Last Day
455,933
Last Week
13,237,319
Last Month
54,749,364
Last Year
683,044,131
GitHub Statistics
17,642 Stars
445 Commits
564 Forks
122 Watching
6 Branches
46 Contributors
Bundle Size
752.00 B
Minified
436.00 B
Minified + Gzipped
Package Meta Information
Latest Version
2.5.1
Package Id
classnames@2.5.1
Unpacked Size
23.03 kB
Size
8.46 kB
File Count
10
NPM Version
10.2.3
Node Version
20.10.0
Publised On
29 Dec 2023
Total Downloads
Cumulative downloads
Total Downloads
2,771,307,849
Last day
-13.5%
455,933
Compared to previous day
Last week
-4.6%
13,237,319
Compared to previous week
Last month
-7.8%
54,749,364
Compared to previous month
Last year
6.4%
683,044,131
Compared to previous year
Daily Downloads
Weekly Downloads
Monthly Downloads
Yearly Downloads
Classnames
A simple JavaScript utility for conditionally joining classNames together.
Install from the npm registry with your package manager:
1npm install classnames
Use with Node.js, Browserify, or webpack:
1const classNames = require('classnames'); 2classNames('foo', 'bar'); // => 'foo bar'
Alternatively, you can simply include index.js
on your page with a standalone <script>
tag and it will export a global classNames
method, or define the module if you are using RequireJS.
Project philosophy
We take the stability and performance of this package seriously, because it is run millions of times a day in browsers all around the world. Updates are thoroughly reviewed for performance implications before being released, and we have a comprehensive test suite.
Classnames follows the SemVer standard for versioning.
There is also a Changelog.
Usage
The classNames
function takes any number of arguments which can be a string or object.
The argument 'foo'
is short for { foo: true }
. If the value associated with a given key is falsy, that key won't be included in the output.
1classNames('foo', 'bar'); // => 'foo bar'
2classNames('foo', { bar: true }); // => 'foo bar'
3classNames({ 'foo-bar': true }); // => 'foo-bar'
4classNames({ 'foo-bar': false }); // => ''
5classNames({ foo: true }, { bar: true }); // => 'foo bar'
6classNames({ foo: true, bar: true }); // => 'foo bar'
7
8// lots of arguments of various types
9classNames('foo', { bar: true, duck: false }, 'baz', { quux: true }); // => 'foo bar baz quux'
10
11// other falsy values are just ignored
12classNames(null, false, 'bar', undefined, 0, 1, { baz: null }, ''); // => 'bar 1'
Arrays will be recursively flattened as per the rules above:
1const arr = ['b', { c: true, d: false }]; 2classNames('a', arr); // => 'a b c'
Dynamic class names with ES2015
If you're in an environment that supports computed keys (available in ES2015 and Babel) you can use dynamic class names:
1let buttonType = 'primary'; 2classNames({ [`btn-${buttonType}`]: true });
Usage with React.js
This package is the official replacement for classSet
, which was originally shipped in the React.js Addons bundle.
One of its primary use cases is to make dynamic and conditional className
props simpler to work with (especially more so than conditional string manipulation). So where you may have the following code to generate a className
prop for a <button>
in React:
1import React, { useState } from 'react'; 2 3export default function Button (props) { 4 const [isPressed, setIsPressed] = useState(false); 5 const [isHovered, setIsHovered] = useState(false); 6 7 let btnClass = 'btn'; 8 if (isPressed) btnClass += ' btn-pressed'; 9 else if (isHovered) btnClass += ' btn-over'; 10 11 return ( 12 <button 13 className={btnClass} 14 onMouseDown={() => setIsPressed(true)} 15 onMouseUp={() => setIsPressed(false)} 16 onMouseEnter={() => setIsHovered(true)} 17 onMouseLeave={() => setIsHovered(false)} 18 > 19 {props.label} 20 </button> 21 ); 22}
You can express the conditional classes more simply as an object:
1import React, { useState } from 'react'; 2import classNames from 'classnames'; 3 4export default function Button (props) { 5 const [isPressed, setIsPressed] = useState(false); 6 const [isHovered, setIsHovered] = useState(false); 7 8 const btnClass = classNames({ 9 btn: true, 10 'btn-pressed': isPressed, 11 'btn-over': !isPressed && isHovered, 12 }); 13 14 return ( 15 <button 16 className={btnClass} 17 onMouseDown={() => setIsPressed(true)} 18 onMouseUp={() => setIsPressed(false)} 19 onMouseEnter={() => setIsHovered(true)} 20 onMouseLeave={() => setIsHovered(false)} 21 > 22 {props.label} 23 </button> 24 ); 25}
Because you can mix together object, array and string arguments, supporting optional className
props is also simpler as only truthy arguments get included in the result:
1const btnClass = classNames('btn', this.props.className, {
2 'btn-pressed': isPressed,
3 'btn-over': !isPressed && isHovered,
4});
Alternate dedupe
version
There is an alternate version of classNames
available which correctly dedupes classes and ensures that falsy classes specified in later arguments are excluded from the result set.
This version is slower (about 5x) so it is offered as an opt-in.
To use the dedupe version with Node.js, Browserify, or webpack:
1const classNames = require('classnames/dedupe');
2
3classNames('foo', 'foo', 'bar'); // => 'foo bar'
4classNames('foo', { foo: false, bar: true }); // => 'bar'
For standalone (global / AMD) use, include dedupe.js
in a <script>
tag on your page.
Alternate bind
version (for css-modules)
If you are using css-modules, or a similar approach to abstract class 'names' and the real className
values that are actually output to the DOM, you may want to use the bind
variant.
Note that in ES2015 environments, it may be better to use the "dynamic class names" approach documented above.
1const classNames = require('classnames/bind'); 2 3const styles = { 4 foo: 'abc', 5 bar: 'def', 6 baz: 'xyz', 7}; 8 9const cx = classNames.bind(styles); 10 11const className = cx('foo', ['bar'], { baz: true }); // => 'abc def xyz'
Real-world example:
1/* components/submit-button.js */ 2import { useState } from 'react'; 3import classNames from 'classnames/bind'; 4import styles from './submit-button.css'; 5 6const cx = classNames.bind(styles); 7 8export default function SubmitButton ({ store, form }) { 9 const [submissionInProgress, setSubmissionInProgress] = useState(store.submissionInProgress); 10 const [errorOccurred, setErrorOccurred] = useState(store.errorOccurred); 11 const [valid, setValid] = useState(form.valid); 12 13 const text = submissionInProgress ? 'Processing...' : 'Submit'; 14 const className = cx({ 15 base: true, 16 inProgress: submissionInProgress, 17 error: errorOccurred, 18 disabled: valid, 19 }); 20 21 return <button className={className}>{text}</button>; 22}
Polyfills needed to support older browsers
classNames >=2.0.0
Array.isArray
: see MDN for details about unsupported older browsers (e.g. <= IE8) and a simple polyfill.
LICENSE MIT
Copyright (c) 2018 Jed Watson. Copyright of the Typescript bindings are respective of each contributor listed in the definition file.
No vulnerabilities found.
Reason
29 commit(s) and 0 issue activity found in the last 90 days -- score normalized to 10
Reason
all changesets reviewed
Reason
no binaries found in the repo
Reason
no dangerous workflow patterns detected
Reason
license file detected
Details
- Info: project has a license file: LICENSE:0
- Info: FSF or OSI recognized license: MIT License: LICENSE:0
Reason
packaging workflow detected
Details
- Info: Project packages its releases by way of GitHub Actions.: .github/workflows/release.yml:10
Reason
1 existing vulnerabilities detected
Details
- Warn: Project is vulnerable to: GHSA-952p-6rrq-rcjv
Reason
dependency not pinned by hash detected -- score normalized to 2
Details
- Warn: GitHub-owned GitHubAction not pinned by hash: .github/workflows/node.js.yml:22: update your workflow using https://app.stepsecurity.io/secureworkflow/JedWatson/classnames/node.js.yml/main?enable=pin
- Warn: GitHub-owned GitHubAction not pinned by hash: .github/workflows/node.js.yml:25: update your workflow using https://app.stepsecurity.io/secureworkflow/JedWatson/classnames/node.js.yml/main?enable=pin
- Warn: GitHub-owned GitHubAction not pinned by hash: .github/workflows/node.js.yml:42: update your workflow using https://app.stepsecurity.io/secureworkflow/JedWatson/classnames/node.js.yml/main?enable=pin
- Warn: GitHub-owned GitHubAction not pinned by hash: .github/workflows/node.js.yml:45: update your workflow using https://app.stepsecurity.io/secureworkflow/JedWatson/classnames/node.js.yml/main?enable=pin
- Warn: GitHub-owned GitHubAction not pinned by hash: .github/workflows/node.js.yml:62: update your workflow using https://app.stepsecurity.io/secureworkflow/JedWatson/classnames/node.js.yml/main?enable=pin
- Warn: GitHub-owned GitHubAction not pinned by hash: .github/workflows/node.js.yml:65: update your workflow using https://app.stepsecurity.io/secureworkflow/JedWatson/classnames/node.js.yml/main?enable=pin
- Warn: GitHub-owned GitHubAction not pinned by hash: .github/workflows/release.yml:17: update your workflow using https://app.stepsecurity.io/secureworkflow/JedWatson/classnames/release.yml/main?enable=pin
- Warn: GitHub-owned GitHubAction not pinned by hash: .github/workflows/release.yml:23: update your workflow using https://app.stepsecurity.io/secureworkflow/JedWatson/classnames/release.yml/main?enable=pin
- Info: 0 out of 8 GitHub-owned GitHubAction dependencies pinned
- Info: 3 out of 3 npmCommand dependencies pinned
Reason
no effort to earn an OpenSSF best practices badge detected
Reason
detected GitHub workflow tokens with excessive permissions
Details
- Warn: no topLevel permission defined: .github/workflows/node.js.yml:1
- Info: no jobLevel write permissions found
Reason
security policy file not detected
Details
- Warn: no security policy file detected
- Warn: no security file to analyze
- Warn: no security file to analyze
- Warn: no security file to analyze
Reason
project is not fuzzed
Details
- Warn: no fuzzer integrations found
Reason
SAST tool is not run on all commits -- score normalized to 0
Details
- Warn: 0 commits out of 30 are checked with a SAST tool
Score
6.2
/10
Last Scanned on 2024-12-16
The Open Source Security Foundation is a cross-industry collaboration to improve the security of open source software (OSS). The Scorecard provides security health metrics for open source projects.
Learn MoreOther packages similar to classnames
@types/classnames
Stub TypeScript definitions entry for classnames, which provides its own types definitions
prefix-classnames
classnames with prefix
clsx
A tiny (239B) utility for constructing className strings conditionally.
@elliemae/ds-classnames
ICE MT - Dimsum Library - Aggregated classNames to component