Last Updated: February 25, 2016
·
430
· rjz

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 ...'

[1]: https://github.com/facebook/react/blob/9484d0fc39b301916ae3ae14913ca01fc42cf05b/docs/docs/10.3-class-name-manipulation.md