Reputation: 87
I have read in React docs that keys are not globally unique and that they should be unique per siblings, but why does this code work?
import React from 'react'
import ReactDOM from 'react-dom'
const people = [
{name: 'John', age: 20},
{name: 'Danny', age: 35},
{name: 'Rebecca', age: 18},
]
const element = (
<ul>
{people.map((person, index) => (
<li key={index}>{person.name}</li>
))}
{people.map((person, index) => (
<li key={index}>{person.name}</li>
))}
</ul>
)
ReactDOM.render(
element,
document.getElementById("root")
)
Aren't all of the resultant <li>
elements considered siblings, so why I do not get any warning that there are two elements with the same key?
Upvotes: 2
Views: 102
Reputation: 23064
I think the way the word "siblings" is used in the docs refers to siblings in a javascript Array, which might not correspond to siblings in in the rendered DOM tree. So it doesn't matter that the <li/>
nodes will be rendered into the same <ul/>
parent, React will see them as two different arrays of components.
Keys Must Only Be Unique Among Siblings
Keys used within arrays should be unique among their siblings. However they don’t need to be globally unique. We can use the same keys when we produce two different arrays.
https://reactjs.org/docs/lists-and-keys.html#keys-must-only-be-unique-among-siblings
Upvotes: 2