sfletche
sfletche

Reputation: 49714

Getting key prop warning in React, even though component is not repeated

I have a list of components (all containing a unique key prop) spread into another list where another component is added at the end.

const myComponents = [<myComponent key={1} />, <myComponent key={2} />];
...
return [...myComponents, <myOtherComponent />]

I didn't think the myOtherComponent would require a key prop, but I still get the warning Each child in an array or iterator should have a unique "key" prop.

Am I wrong in thinking the key prop should be unnecessary in this case?

...should an array containing a single component ([<myOtherComponent />]) require a key prop?

Upvotes: 1

Views: 99

Answers (2)

Sventies
Sventies

Reputation: 2756

As soon as your elements are in an array, this warning will pop up.

Upvotes: 0

Andy Ray
Andy Ray

Reputation: 32066

Anything in an array needs a key when rendered by React. <myOtherComponent key={0}/>

Upvotes: 4

Related Questions