How to provide dynamic className to element in React Class render method

Take a look at the classnames package. You can do stuff like this:

className={classNames('alert', `alert-${type}`)}

or

className={classNames({
    'alert': true,
    'alert-success': success,
    'alert-error': error
})

Looks like I have found answer to my question. We can simply do something like this:

var Alert = ReactClass({
  render: function() {
    return <div className={"alert " + this.props.type}>{this.props.message}</div>
  }
});

Just put your classes inside Template evaluators { } in this case. Create your class string based on your props and states.

Hope this is helpful to others.


One way to accomplish this is to have a string which will contain all of your classes and then set it to the Component's className:

var Alert = ReactClass({

  var yourClassName = 'alert ';

  // Add any additional class names
  yourClassName += this.props.type + ' ';

  render: function() {
    return <div className={yourClassName}>{this.props.message}</div>
  }
});

or alternatively you can store your class names in an array and convert it to a class friendly string when you're ready to use it:

var Alert = ReactClass({

  var yourClassArray = [];

  // Add any additional class names
  yourClassArray.push('alert');
  yourClassArray.push(this.props.type);

  var classString = yourClassArray.join(' ');

  render: function() {
    return <div className={classString}>{this.props.message}</div>
  }
});