Skip to content

Instantly share code, notes, and snippets.

@joecritch
Last active August 29, 2015 14:04
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save joecritch/c4ae91c3e5e56bc48cac to your computer and use it in GitHub Desktop.
Save joecritch/c4ae91c3e5e56bc48cac to your computer and use it in GitHub Desktop.
An improved React cx.js that supports nested arrays, which allows for dynamic keys
// Improved on react/lib/cx.js
// by supporting nested arrays to allow for dynamic keys
function cx(classNames) {
if(classNames instanceof Array) {
var filteredClasses = [];
classNames.forEach(function(className, i) {
if(typeof className === 'string') {
filteredClasses.push(className);
}
else if(typeof className[1] === 'undefined' || !!className[1]) {
filteredClasses.push(className[0]);
}
});
return Array.prototype.join.call(filteredClasses, ' ');
}
else if(typeof classNames === 'object') {
return Object.keys(classNames).filter(function(className) {
return classNames[className];
}).join(' ');
} else {
return Array.prototype.join.call(arguments, ' ');
}
}
module.exports = cx;
// Basic example of how to use the Array-based syntax.
// Note the optional nested arrays, where the string is assumed as truthy
{
className: cx([
'block',
['block--active', this.state.isActive],
'block--key' + key
])
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment