Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Way to check if first iteration in map

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>
)
like image 224
curv Avatar asked Dec 22 '15 14:12

curv


1 Answers

If 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

like image 66
Oleksandr T. Avatar answered Oct 13 '22 04:10

Oleksandr T.