5

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

2

3 Answers 3

17

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}
    />
  );
})}
Sign up to request clarification or add additional context in comments.

1 Comment

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

Comments

0

use the second parameters from map function.

{this.state.fields.map((field, index) => (
    <IssueInputRow
        labelText={field.name}
        key={index}                  
        handler={this.handler}
    />)
)}

1 Comment

This is very similar to the accepted answer, with only minor syntactical differences. If you believe the alternate syntax you've used adds something significant, please explain why the asker might want to use your version over the alternative. Otherwise, this answer will (likely) be deleted.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.