最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - Way to check if first iteration in map - Stack Overflow

programmeradmin5浏览0评论

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
  • 1 Can you explain where your map function is being used? It's not present in the code snippet. – adrianp Commented Dec 22, 2015 at 14:32
  • 2 the second argument for the map callback function is the index, so you can check if the index is zero: developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/… – patrick Commented Dec 22, 2015 at 14:34
Add a comment  | 

2 Answers 2

Reset to default 22

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

Here is a slight simplification of the accepted answer for the general case:

items.map(item, index) => {
  if (index === 0) {
    // First item...
  }
  // ...
}
发布评论

评论列表(0)

  1. 暂无评论