NOTE: I do understand the importance of keys
in arrays. Normally I use .map for repeating over an array and use the index
variable .map
provides. In my case I have no access to any index variable. I want to know a better way than manually adding keys.
So I was doing this:
function AComponent() {
return <div>
<BComponent />
<BComponent />
</div>
}
function BComponent() {
return [
<h2>Title</h2>,
<p>Description </p>
]
}
Which throws an error
Warning: Each child in an array or iterator should have a unique "key" prop. See https://reactjs.org/docs/lists-and-keys.html#keys for more information. in BComponent (created by AComponent)
So I needed to change the BComponent
as:
function BComponent() {
// I added the key attribute to each element in the array
return [
<h2 key="1">Title</h2>,
<p key="2">Description </p>
]
}
Definitely, this is not the best way to fix this. I want to know what's the better way? Or is this a bug from React?