Reputation: 6498
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
?
Upvotes: 8
Views: 26821
Reputation: 86260
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.
Upvotes: 9
Reputation: 201
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
Upvotes: 3
Reputation: 10629
You can use this:
var classes = {
'large_prod_modal': true,
'hidden': true
};
classes[large_prod_class] = true;
var modal_classes = cx(classes);
You can see this documentation about adding dynamic properties to objects at run time (dynamically):
This notation is also very useful when property names are to be dynamically determined (when the property name is not determined until runtime).
Upvotes: 0