I encountered a duplicate key warning that I did not expect(because it’s not a list of the same type of components) for the following:
<Foo key={'baz'} />
<Bar key={'baz'} />
- Why it’s totally fine to have the following?
<Foo />
<Bar />
- Why it’s problematic for the react fiber to consider component type when handling key uniqueness?
- Could this be because there is some advanced use case where a developer might want to have the same key for different types of components?
It’s all clear regarding keys and lists, just curious how it works under the hood.
2
Answers
I think it doesn’t matter which component type you would use.
Consider the following code:
If you are iterating in order to create that you will get warnings to provide unique keys for each node inside the parent node.
If they are siblings, they are still children of another parent element. So they are still technically children.
This would trigger a:
Warning: Each child in a list should have a unique “key” prop.
As expected, we are presented with the following error:
Chris’ response to "Understanding unique keys for array children in React.js" explains all you need to know about they
key
prop.He cites the React docs:
Keys Must Only Be Unique Among Siblings
In conclusion, since they are siblings (disregarding component type), each
key
prop should be unique.Since we can re-use keys (non-global), we can actually do the following:
Note: Keep in mind that you should only have to supply a key when mapping over an array of items.