In react.js I need to add a dynamic class name to a div
.
Using react-addons, I tried it the following way but in vain:
var addons = require('react-addons');
var cx = addons.classSet;
var Overlay = React.createClass({
render: function() {
var prod_id = this.props.prop_id;
var large_prod_class = 'large_prod_modal_' + prod_id;
var modal_classes = cx({
'large_prod_modal': true,
large_prod_class: true,
'hidden': true
});
return (<div className={modal_classes}>lorem ipsum</div>);
}
});
And Overlay
component is used in the following way:
<Overlay prod_id="9" />
The prop (i.e: prod_id
) value is random however. I do not get the large_prod_modal_9
class for the div
. All the classes I get are large_prod_modal
,large_prod_class
and hidden
How to get the large_prod_modal_9
class for the div
?
To do that, first we create a class and assign it to HTML elements on which we want to apply CSS property. We can use className and classList property in JavaScript. Approach: The className property used to add a class in JavaScript.
Use a template literal to dynamically add CSS classes to React elements. Template literals are delimited with backticks and allow us to embed variables and expressions using the dollar sign and curly braces ${expression} syntax.
Using . add() method: This method is used to add a class name to the selected element.
The classSet addon is deprecated as of 0.13. The offical recomendation is to use JedWatson/classnames.
var cx = require('classnames');
var Overlay = React.createClass({
render: function() {
var prod_id = this.props.prop_id;
var modal_classes = cx('large_prod_modal_' + prod_id, {
'large_prod_modal': true,
'hidden': true
});
return (<div className={modal_classes}>lorem ipsum</div>);
}
});
If all of the class names are always true, you can just pass them as strings.
var prod_id = this.props.prop_id;
var modal_classes = cx(
'large_prod_modal_' + prod_id,
'large_prod_modal'
'hidden'
});
You can mix strings and objects as desired. You don't get this flexibility with the addon classSet.
example solution for this would be:
dynamicClass: function(){
return "large_prod_modal large_prod_modal_" + this.props.prod_id + " hidden"
}
render: function(){
return (<div className={this.dynamicClass()}>lorem ipsum</div>)
}
You can't generate dynamicly the key in JSON object so thats why you get 'large_prod_class' and it's correct
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