Building React classNames with CoffeeScript
Maybe you're tired of building CSS classes from concatenated strings [[1]]:
render: function() {
var classString = 'message';
if (this.props.isImportant) {
classString += ' message-important';
}
if (this.props.isRead) {
classString += ' message-read';
}
// 'message message-important message-read'
return <div className={classString}>Great, I'll be there.</div>;
}
With pure JavaScript, you could replace this logic with a library like classnames
:
var classString = classNames({
'message': true,
'message-important': this.props.isImportant,
'message-read': this.props.isRead
}); // => 'message ...'
But if you're using CoffeeScript, you can sugar things up with array conditionals—no libraries (even turnkey ones) required:
classString = [
'message'
'message-important' if @props.isImportant
'message-read' if @props.isRead
].join(' ') # => 'message ...'
Written by RJ Zaworski
Related protips
Have a fresh tip? Share with Coderwall community!
Post
Post a tip
Best
#Coffeescript
Authors
iam4x
94.17K
ericdfields
63.02K
Sponsored by #native_company# — Learn More
#native_title#
#native_desc#