Way to check if first iteration in map

- 1 answer

Ad

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>
)
Ad

Answer

Ad

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

Ad
source: stackoverflow.com
Ad