Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Assign position in array as react key?

I have an array which consists of different strings. I want to map through it and display it in React. React does not like it when two strings are the same.

My question is this: Is there a way for me to map through the array and assign the position of the element in the array (0,1,2,3..) as the key? I am not sure how I would access this? Can I?

let renderthis = this.props.myreducer.somearray.map((element) =>
  <span key={what can I put here?}>{element} </span>
);

I tried this btw, but it did not work:

let renderthis = this.props.myreducer.somearray.map((element, i) =>
  <span key={i}>{element} </span>
);

Warning: flattenChildren(...): Encountered two children with the same key, .1:$afaf. Child keys must be unique; when two children share a key, only the first child will be used.

like image 848
George Welder Avatar asked Dec 06 '25 20:12

George Welder


1 Answers

Array.prototype.map callback accepts the second argument as an item index.

That means that if you simply need unique keys per a collection of element and you don't have any other values that are naturally unique you can simply do:

let renderthis = this.props.myreducer.somearray.map((element, i) =>
  <span key={i}>{element} </span>
);
like image 126
zerkms Avatar answered Dec 08 '25 08:12

zerkms



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!