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?
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.
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.
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>
}
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);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With