Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to map through an array in React without ids?

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>); })}
like image 766
George Welder Avatar asked Oct 30 '25 03:10

George Welder


1 Answers

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

like image 80
w00t Avatar answered Oct 31 '25 18:10

w00t



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!