Last active
August 29, 2015 14:04
-
-
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
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// 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; |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// 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