Skip to content
Conditionally join CSS class names together - Especially useful with React
JavaScript TypeScript
Branch: master
Clone or download
Latest commit 6de3b16 May 28, 2019
Permalink
Type Name Latest commit message Commit time
Failed to load latest commit information.
.github Create funding.yml May 28, 2019
.editorconfig Init Jun 20, 2018
.gitattributes Init Jun 20, 2018
.gitignore Init Jun 20, 2018
.npmrc Init Jun 20, 2018
.travis.yml Add TypeScript definition (#3) Apr 27, 2019
index.d.ts Meta tweaks Apr 27, 2019
index.js Add TypeScript definition (#3) Apr 27, 2019
index.test-d.ts Add TypeScript definition (#3) Apr 27, 2019
license Init Jun 20, 2018
package.json 1.1.0 Apr 27, 2019
readme.md Meta tweaks Apr 27, 2019
test.js Init Jun 20, 2018

readme.md

class-names Build Status gzip size

Conditionally join CSS class names together - Especially useful with React

Install

$ npm install @sindresorhus/class-names

Usage

const classNames = require('@sindresorhus/class-names');

classNames('unicorn', 'rainbow');
//=> 'unicorn rainbow'

classNames({awesome: true, foo: false}, 'unicorn', {rainbow: false});
//=> 'awesome unicorn'

classNames('unicorn', null, undefined, 0, 1, {foo: null});
//=> 'unicorn'

const buttonType = 'main';
classNames({[`button-${buttonType}`]: true});
//=> 'button-main'
const classNames = require('@sindresorhus/class-names');

const Button = props => {
	console.log(props);
	/*
	{
		type: 'success',
		small: true
	}
	*/

	const buttonClass = classNames(
		'button',
		{
			[`button-${props.type}`]: props.type,
			'button-block': props.block,
			'button-small': props.small
		}
	);

	console.log(buttonClass);
	//=> 'button button-success button-small'

	return <button className={buttonClass}>…</button>;
};

API

classNames(…input)

Conditionally join CSS class names together.

input

Type: string | object

Accepts a combination of strings and objects. When an object, only object keys with truthy values are included. Anything else is ignored.

FAQ

How is it different from classnames?

  • Dedupes by default.
  • Doesn't coerce numbers to strings.
  • Doesn't support array input. Just use the spread operator.

Related

  • react-extras - Useful components and utilities for working with React

License

MIT © Sindre Sorhus

You can’t perform that action at this time.