In a child-less React component, I'm getting the "unique key prop" error due to my use of an array inside a JSX conditional:
Each child in an array should have a unique "key" prop.
The code that's triggering the error looks like this:
<dl>
{ item.sale ?
[<dt>Sale</dt>,<dd className="formatted">{item.sale}</dd>,<dt>SRP</dt>,<dd>{item.srp}</dd>] :
[<dt>Price</dt>,<dd className="formatted">{item.srp}</dd>]
}
</dl>
I understand why the key prop is needed when rendering child components, but how do I satisfy React/JSX when the "child in an array" is an arbitrary set of child elements like this?
Finally we can add a Key prop to the <li> elements and simply call the function uuid() . This function returns a string which is a UUID. That's it. That's all there is to it.
It is therefore very important that the key always remains unique, otherwise there is a good chance React will mix up the elements and mutate the incorrect one. It is also important that these keys remain static throughout all re-renders in order to maintain best performance.
Using array indexes for keys is a great way to give each element in a list a unique key if you don't have an id property on your data. However, if the order of the elements can be changed, this can cause issues in React. Think of adding, removing, reordering, or filtering elements, such as when working with filters.
React's key prop gives you the ability to control component instances. Each time React renders your components, it's calling your functions to retrieve the new React elements that it uses to update the DOM. If you return the same element types, it keeps those components/DOM nodes around, even if all the props changed.
React can't know that your array is static, so you get the warning. The most practical thing to do here is to write something like:
var dl;
if (item.sale) {
dl = <dl key="sold">
<dt>Sale</dt>
<dd className="formatted">{item.sale}</dd>
<dt>SRP</dt>
<dd>{item.srp}</dd>
</dl>;
} else {
dl = <dl key="unsold">
<dt>Price</dt>
<dd className="formatted">{item.srp}</dd>
</dl>;
}
Providing the keys on the root tells React how it should reconcile the lists when item.sale
changes.
I tend to find this easier to read as well.
I also had a similar issue and I solved the problem adding key={index}
in the following code.
this.state.shopList.map((shop, index) => {
return (
<Table.Row key={index}>
<Table.Cell collapsing>{shop.shopName}</Table.Cell>
<Table.Cell collapsing>{shop.email}</Table.Cell>
<Table.Cell collapsing>{shop.shopAddress}</Table.Cell>
<Table.Cell collapsing>{shop.approved}</Table.Cell>
<Table.Cell collapsing>{shop.iban}</Table.Cell>
</Table.Row>
);
})}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With