Sergei Basharov
Sergei Basharov

Reputation: 53850

How to assign a class to an element if variable == something in React?

I am new to React, worked with Angular a lot before. In Angular it's as simple as possible to assign some class depending on variables like this:

<p ng-class="{warning: warningLevel==3, critical: warningLevel==5}">Mars attacks!</p>

How can I do a similar thing inside a template with React?

Upvotes: 5

Views: 9308

Answers (2)

Brigand
Brigand

Reputation: 86220

An alternative to classSet is often using a simple object lookup.

var levelToClass = {
  "3": "warning",
  "5": "critical"
};

// ...
render: function(){
  var level = levelToClass[this.props.warningLevel] || "";
  return <p className={"message " + level}>Test</p>
}

Or in some cases a ternary:

render: function(){
  var level = this.props.warningLevel === 3 ? "warning"
            : this.props.warningLevel === 5 ? "critical"
            : "";
  return <p className={"message " + level}>Test</p>
}

Upvotes: 5

okonetchnikov
okonetchnikov

Reputation: 274

Short answer: use classSet(): http://facebook.github.io/react/docs/class-name-manipulation.html

Longer answer:

It's not much different in React, besides you write a plain old JavaScript, so lots of control here. Also, React already has a nifty addon to make it even easier. In this case your component will look something like this:

var ClassnameExample = React.createClass({
  render: function() {
    var cx = React.addons.classSet;
    var classes = cx({
      "message": true,
      "warning": this.props.warningLevel === "3",
      "critical": this.props.warningLevel === "5"
    });
    return <p className={classes}>Test</p>;
  }
});

Here is the working example: http://jsbin.com/lekinokecoge/1/edit?html,css,js,output

Just try to change the value here:

React.renderComponent(<ClassnameExample warningLevel="3" />, document.body);

Upvotes: 4

Related Questions