I'm trying to add a class to an element within ReactJS using the map function, but ONLY for the first one in the loop, is this possible / an easy way?
return (
<div key={itemData.itemCode} className="item active">
Want to add 'active' class when the first but for the others dont add it
</div>
)
I'm trying to add a class to an element within ReactJS using the map function, but ONLY for the first one in the loop, is this possible / an easy way?
return (
<div key={itemData.itemCode} className="item active">
Want to add 'active' class when the first but for the others dont add it
</div>
)
Share
Improve this question
edited Dec 22, 2015 at 14:37
thanksd
55.6k23 gold badges165 silver badges154 bronze badges
asked Dec 22, 2015 at 14:24
curvcurv
3,8444 gold badges34 silver badges48 bronze badges
2
|
2 Answers
Reset to default 22If you use .map
or .forEach
then you can do it like this
var List = React.createClass({
render: function() {
var lists = this.props.data.map(function (itemData, index) {
/// if index === 0 ( it is first element in array ) then add class active
var cls = (index === 0) ? 'item active' : 'item';
return <div key={itemData.itemCode} className={ cls }>
{ itemData.itemValue }
</div>;
})
return <div>{ lists }</div>;
}
});
Example
also there is good package called classnames
if you need conditionally change classes, like as in your case
var List = React.createClass({
render: function() {
var lists = this.props.data.map(function (itemData, index) {
return <div
key={itemData.itemCode}
className={ classnames('item', { active: index === 0 }) }>
{ itemData.itemValue }
</div>
})
return <div>{ lists }</div>;
}
});
Example
Here is a slight simplification of the accepted answer for the general case:
items.map(item, index) => {
if (index === 0) {
// First item...
}
// ...
}
map
function is being used? It's not present in the code snippet. – adrianp Commented Dec 22, 2015 at 14:32