10

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>
)
2
  • 1
    Can you explain where your map function is being used? It's not present in the code snippet. 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/… Commented Dec 22, 2015 at 14:34

2 Answers 2

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

Sign up to request clarification or add additional context in comments.

Comments

1

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

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.