1

I am mapping through an array, and I want my variable i to be used as a unique key for my Components, however I do not know how (or where) to increment it correctly, if I add a {i++} within the <Component> tags then it will display the value of i on screen, and if I instead add {this.function(i)} and place the i++ inside the function, it will call the function but the variable i will reinitiate to the value of 0 everytime, so the key value will not be unique. I need the value of i to be the key for the component and it has to be incremented by 1 everytime, does anyone know how I can achieve this? Also, as you can see in the code, when the component is clicked it will make a function call which will send the value of i of the clicked component as a parameter to the called function.

Code:

  function(i) {
    console.log(i)
  }

  render() {

  var i = 0;
  var {array} = this.state;

  return (
    <div className="App">
    {array.map(item => (
      <Component key={i} onClick={(e) => this.function(i, e)}>
        <p>{item.name}</p>
      </Component>
    ))}
    </div>
  );
}

3 Answers 3

2

The map function gets a second parameter which is the index of the element:

{array.map((item, i) => (
  <Component key={i} onClick={(e) => this.function(i, e)}>
    <p>{item.name}</p>
  </Component>
)}

Be aware that if you intend to sort this array or change its contents at runtime, then using array index as a key can cause some mistakes, as sometimes an old component will be mistake for a new one. If it's just a static array though, then using index as a key shouldn't be a problem.

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

1 Comment

Oh my goodness, I feel so dumb, because I actually tried this method but I always used to get an error, and I just realized why, I always added the ) after i but never added the ( before item so I would close the parentheses without opening it....
2

.map already offer the increment, just add a second variable to the callback

  render() {
  var {array} = this.state;

  return (
    <div className="App">
    {array.map((item,i) => (
      <Component key={i} onClick={(e) => this.function(i, e)}>
        <p>{item.name}</p>
      </Component>
    ))}
    </div>
  );
}

Comments

1

You could try array.map((x, Key) => console.log(key)); .. In place of console.log you could add your code, it should work fine as per your requirement.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.