5

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?

2 Answers 2

5

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>
}
Sign up to request clarification or add additional context in comments.

Comments

4

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);

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.