I am mapping arrays without adding keys to the children which cause this error.
react_devtools_backend.js:4026 Warning: Each child in a list should have a unique "key" prop.
how can I get rid of this error with these structure only without anything specific to each child in each mapping!
Here is my array structure:
[
[
{ title: 'McRoyale', price: 70, count:5, totalPrice: 350 },
{ title: 'Big Mac', price: 55, count:1, totalPrice: 55 },
],
[
{ title: 'Double Big Tasty', price: 99, count:2, totalPrice: 198 },
],
[
{ title: 'Grand Chicken Premier', price: 72, count:3, totalPrice: 216 },
{ title: 'Spicy Chicken Fillet', price: 60, count:2, totalPrice: 120 },
]
]
and here is my code:
<tbody>
{cardItems.map((items) => (
<tr>
<td>
{items.map((item) => (
<>
<b className='mc-red'>{item.title}</b> Item Price:{' '}
{item.price} LE, Item Count: {item.count}, Item Total Price:{' '}
{item.totalPrice} LE
<br />
</>
))}
</td>
<td>{calcPrice(items)} LE</td>
</tr>
))}
</tbody>
JSX elements that are dynamically created (e.g. using map) must have a key prop, according to the official doc.
Another note is that, this key must be consistent even if the dynamic logic changes. For example, you can't use the element's index in the array as a key because that can change. You must use some value that is consistent.
With that in mind, it is simple to use each item's title as the key for you inner map. For the outer map though, if you can ensure items never changes:
// This never changes
[
{ title: 'McRoyale', price: 70, count:5, totalPrice: 350 },
{ title: 'Big Mac', price: 55, count:1, totalPrice: 55 },
]
then you can use the all its items' titles to make the key, like this:
import { Fragment } from 'react';
<tbody>
{cardItems.map((items) => (
<tr key={items.map((item) => item.title).join('')}>
<td>
{items.map((item) => (
<Fragment key={item.title}>
<b className="mc-red">{item.title}</b> Item Price: {item.price}{' '}
LE, Item Count: {item.count}, Item Total Price:{' '}
{item.totalPrice} LE
<br />
</Fragment>
))}
</td>
<td>{calcPrice(items)} LE</td>
</tr>
))}
</tbody>