sfletche sfletche - 4 months ago 29
Javascript Question

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?

Answer Source

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