3

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.

8
  • The second argument to the map callback is an index. Commented May 5, 2017 at 0:49
  • thanks. see my edit, if this is what you mean. I tried that but I get a warning that the elements have duplicate keys. But maybe what I am doing there is wrong? Commented May 5, 2017 at 0:53
  • It's some other elements that have duplicate keys then. Commented May 5, 2017 at 0:55
  • I dont think so. I am getting that error at precisely the moment I add a duplicate element to that array. Commented May 5, 2017 at 0:56
  • Not sure where you took the .1:$afaf. i is a number there. Commented May 5, 2017 at 0:57

1 Answer 1

2

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.