conditionally construct className strings
$ npm i @thomann/classnames
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.
Boolean
Number
String
Array
Object
Function
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'
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'
MIT License, see LICENSE