jgj_yq
Last Updated: February 25, 2016
·
108
· rjz
0b7fb38ae0407a97f5a342ebbcc288f7

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 ...'
Say Thanks
Respond