random1234
random1234

Reputation: 827

React incrementing variable within .map() function

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>
  );
}

Upvotes: 1

Views: 4938

Answers (3)

Aravind Kumar
Aravind Kumar

Reputation: 11

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.

Upvotes: 1

Nicholas Tower
Nicholas Tower

Reputation: 85211

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.

Upvotes: 2

Renaldo Balaj
Renaldo Balaj

Reputation: 2440

.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>
  );
}

Upvotes: 2

Related Questions