Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 302
Sergei Basharov Avatar asked Oct 02 '14 17:10

Sergei Basharov


People also ask

How do I apply a class based on a condition in React?

The simplest approach is to use a ternary statement inside of a template literal. In this example, banner is always on the div , but active depends on the active prop. If you have a lot of class names that need to be conditional on the same element, it can get a little messy, but it still works.

How do you apply conditionally in React CSS?

Create a new react application or open existing react app. Declare two different CSS style objects named as objectStyle and objectStyleValid with below attributes (in Code). Next we will declare a const variable named “isValid”. Based on its value (true/false) we will try to change the CSS style.


2 Answers

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>
}
like image 130
Brigand Avatar answered Oct 29 '22 11:10

Brigand


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);
like image 29
okonetchnikov Avatar answered Oct 29 '22 11:10

okonetchnikov