@chbphone55/classnames
TypeScript icon, indicating that this package has built-in type declarations

2.0.0 • Public • Published

classnames

Dependency Status

Maintainability Rating

Known Vulnerabilities

npm version

downloads

A simple and small JavaScript utility for joining class names together. Made for use with frameworks like React, but can be used how you see fit.

Installation:

npm i @chbphone55/classnames
# or
yarn add @chbphone55/classnames

Usage:

First let's import it

// Node
const { classNames } = require('@chbphone55/classnames');

// ESM
import { classNames } from '@chbphone55/classnames';

Now let's use it

/* STRINGS */
classNames('loading-indicator', 'red-bg');
// => 'loading-indicator red-bg'

/* OBJECTS, falsey values cause extra spaces */
classNames({ animated: 'truthy value', 'inactive-bg': false });
// => 'animated '

/* OBJECTS & STRINGS */
classNames('loading-indicator', { animated: true });
// => 'loading-indicator animated'

/* ARRAYS (recursively flattened) */
classNames(['activated', { nested: true }]);
// => 'activated nested'

/*
  All other types will be ignored but will cause extra spaces
  if they are either, falsey object (null) or not an object/string/array
*/
classNames('test', undefined);
// => 'test '

classNames(null, 'test');
// => ' test'

/* Multiple of same value will not be removed as there is no need */
classNames('test', 'test', 'test');
// => 'test test test'

NOTE: extra spaces will not affect use with DOM elements (includes framework elements like React)

What about using it in React.js?

You simply pass the call to classNames() as the value for the attribute className={}

/* REACT CLASS COMPONENT */
class MyComponent extends React.Component {
  render() {
    const { className } = this.props;
    return <div className={classNames('test', className)}></div>;
  }
}

/* REACT FUNCTION COMPONENT */
function MyComponent({ className }) {
  return <div className={classNames('test', className)}></div>;
}

License

MIT Copyright © 2018 Christopher Brown

Influenced by Jed Watson's classnames

Readme

Keywords

none

Package Sidebar

Install

npm i @chbphone55/classnames

Weekly Downloads

3,479

Version

2.0.0

License

MIT

Unpacked Size

5.81 kB

Total Files

7

Last publish

Collaborators

  • chbphone55