3

Reading this article about using the index is a react key.

Let's say we have two lists:

<List1>
  <el key="1" />
  <el key="2" />
</List1>

<List2>
  <other-el key="1" />
  <other-el key="2" />
</List2>

Is it safe that elements from the two lists have the same keys? Are the keys globally shared between elements or List1 keys are local to first list and List2 keys are local for the second list?

Would it be any better if the lists looked like this:

<List1>
  <el key="1-1" />
  <el key="1-2" />
</List1>

<List2>
  <other-el key="2-1" />
  <other-el key="2-2" />
</List2>
XCS
  • 27,244
  • 26
  • 101
  • 151
  • 11
    Keys only have to be unique amongst singlings. – Felix Kling Nov 01 '17 at 14:14
  • I wrote something similar to the article you linked here on Stack Overflow. I think you'll find it interesting and it will answer your question as well. Link below. – Chris Nov 01 '17 at 14:25
  • Possible duplicate of [Understanding unique keys for array children in React.js](https://stackoverflow.com/questions/28329382/understanding-unique-keys-for-array-children-in-react-js). I understand that you are asking something a bit different, but the answer and more can be found in that post. – Chris Nov 01 '17 at 14:26
  • 1
    @FelixKling true but didn't you wanted to type "siblings" ? :) – Sebastian Voráč MSc. Aug 18 '19 at 21:16

1 Answers1

2

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.

Source: https://reactjs.org/docs/lists-and-keys.html#keys-must-only-be-unique-among-siblings

Mohit Singh
  • 1,452
  • 1
  • 18
  • 27