homerboy homerboy - 3 months ago 18
React JSX Question

Passing in key through `map` function call

I'm receiving a warning about each child in array not having a unique key.

const ITEMS = [
{
"name": "blah", displayName: "Blah!"
"name": "blah1", displayName: "Blah1!"
},
{
"name": "blah2", displayName: "Blah2!"
"name": "blah3", displayName: "Blah3!"
}
]

item: function(i) {
return (
<div key={i.name}>
<h1>{i.displayName}</h1>
</div>
)
}

render: function() {
return (
<div>
{_.chain(ITEMS).map(this.item, this).value()} # I need to pass in a key here?
</div>
)
}


I've posted a similar question about a month ago here: "Each child in an array should have a unique key prop" only on first time render of page. In this case, I need to pass in the key through
map
when it calls the
item()
function. How can I do that?

Answer

JavaScript's map passes the index of the array as the second parameter of the map function.

So, you should be able to just add the index to item:

item: function(currentValue, idx) {
    return (
        <div key={currentValue.name + '-' + idx}>
            <h1>{currentValue.displayName}</h1>
        </div>
    )
}

That will ensure that the key is unique and stable.

In your current implementation, i.name might not be unique. In that case, you will get the warning from react.

Also, this object literal might not do what you are intending:

{
    "name": "blah", displayName: "Blah!"
    "name": "blah1", displayName: "Blah1!"
}

keys like name in an object must be unique or you might get undefined behavior.