4

I have a fairly standard array:

["value","value","value"]

If I want to iterate through it, each list item needs a unique key. But how would I do this in this case?

JSONs often come with an id -but in this case I don't have any id's, and the values also aren't unique, so I cannot just use them as the key.

{someArray.map(object => {
                return (<span key=???> {object} </span>); })}

2 Answers 2

5

You can use the second argument of map, the index:

{someArray.map((object, i) => {
                return (<span key={i}> {object} </span>); })}

As long as someArray remains the same during the lifetime of the component, this is fine; if not, it will cause more re-rendering than necessary when you move, insert or remove items, because all the props of the child change (but in this case you will not notice it at all).

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

1 Comment

You should mention that if you have a unique identifier for an item, you should definitely use it as the key, and should only use the item's index in the case where the array being rendered is static.
1

each list item needs a unique key

It doesn't really. React's warnings here are very over-blown I feel. The unique keys are only needed if you need better performance, and I believe also some stuff about maintaining component state. It's worth noting that if you do dom.div(null, ["text"]) you will receive a warning, but if you do dom.div(null, ...["text"]) you will receive no warning despite the same array being passed in both cases. In the latter case React simply uses the index as the key, which is also totally fine in the former case but React warns about it for no real reason.

If the render function is stateless and you don't need better performance, just give them a key of their index in the array to silence the warning, or use the spread operator.

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.