Skip to content

thomn/classnames

Repository files navigation

@thomann/classnames

npm version types size coverage vulnerabilities dependencies License

conditionally construct className strings

Installation

$ npm i @thomann/classnames

Usage

import classNames from '@thomann/classnames';

classNames('base', {
    'show': true,
    'hide': false
}); // == 'base show'

This library accepts a wide variety of objects and creates a space delimited string for (react) classNames.

Every argument value gets checked for its "truthiness". If a key value pair is given and value is "truthy", its key is going to be used as a classname. If only a string given, its automatically used as a classname.

Supported value types

  • Boolean
  • Number
  • String
  • Array
  • Object
  • Function

Examples

Basic

import classNames from '@thomann/classnames';

const color = 'green';
const size = 'big';
const pos = null;

classNames({
    [color]: color,
    ['font-' + size]: size,
    ['position-' + pos]: pos
}); // == 'green font-big'

Complete

import classNames from '@thomann/classnames';

const string = 'uppercase';
const array = ['italic' , 'bold'];
const object = {icon: true};

classNames(
    'modal',
    {
        'warning': false,
        'show': true,
        'small': array.length >= 1
    },
    object,
    array.map((item) => 'text-' + item),
    {
        ['text-' + string]: string,
        ['font-' + string]: null,
    },
    {
        positive: () => {
            return true;
        },
        negative: () => {
            return false;
        },
    }
); // == 'modal show small icon text-italic text-bold text-uppercase positive'

Licence

MIT License, see LICENSE