4

I am mapping out each field in an array of fields so that each field has an id starting at 1... n number of fields.

I use this as I store all field values in an array, and when a field is changed, I would like data[index] to be updated accordingly.

Here is my code for the map function

{this.state.fields.map((field) => {
return (
    <IssueInputRow
        labelText={field.name}
        key={i}   //want this to increment by 1 for each field, starting a 0                 
        handler={this.handler}
    />
    );
})}

I would like the key for each field to increase by 1 starting at 0. So if there are 3 fields, the keys should be 0,1,2 for the respective fields.

Please let me know how this is possibke

Pranav
  • 149
  • 2
  • 6

2 Answers2

16

The second argument given to the function given to map is the array index, so you could use that.

{this.state.fields.map((field, i) => {
  return (
    <IssueInputRow
      labelText={field.name}
      key={i}             
      handler={this.handler}
    />
  );
})}
Tholle
  • 108,070
  • 19
  • 198
  • 189
1

In JavaScript, map function is having two parameters one is item and second is key. You need to always give both parameters other wise it will shows error in your console. Item will return the value of array and Key will return the subscript value starting from 0.

You can do like this ->

{this.state.fields == undefined ? '' : this.state.fields.map((field, i) => {
    return (
        <IssueInputRow
         labelText={field.name}
         key={i}  //Here key (i) will give you the value starting from 0           
         handler={this.handler}
        />
    );
 })} 

For better understanding of map refer -> enter link description here