I've encountered "Each child in a list should have a unique "key" prop." error. My user data is not dynamic so I use static id for unique key prop.
const App = () => {
const meals = [
{
name: "Kimchi Fried Rice",
info: "Delicious kimch and fresh veggies with rice",
price: 10.99,
id: 1,
},
{
name: "Bibimbap",
info: "Fresh veggies with spicy sauce ",
price: 15.99,
id: 2,
},
{
name: "Ddeok bokki",
info: "Chewy rice cake stirred with spicy sauce",
price: 10,
id: 3,
},
{
name: "Son tofu",
info: "The softest tofu soup ever ",
price: 11.99,
id: 4,
},
];
// console.log(meals.map((a) => a.name));
return (
<div>
<Layout food={meals} />
</div>
);
};
const Layout = (props) => {
return (
<Card>
<div className={classes.frame}>
{props.food.map((menu) => (
<ul>
<li className={classes.name} key={menu.id}>
{menu.name}
</li>
<li className={classes.info}>{menu.info}</li>
<li className={classes.price}>{menu.price}$</li>
<Button> Add</Button>
</ul>
))}
</div>
</Card>
);
};
I initially made this code
<li className={classes.name} key={menu.id}>
{menu.name}
</li>
<li className={classes.info} key={menu.id}>
{menu.info}
</li>
<li className={classes.price} key={menu.id}>
{menu.price}$
</li>
But this error -> Encountered two children with the same key, 1
. Keys should be unique so that components maintain their identity across updates. Non-unique keys may cause children to be duplicated and/or omitted — the behavior is unsupported and could change in a future version.
I tried to use Math.random.().toString() for a key but it just threw a same error.
Could anyone tell me what I am doing wrong?
CodePudding user response:
The list in the error message refers to a list of items rendered by Array.map()
. In your case, each menu
item is a ul
element, so the error message's "child in the list" refers to the ul
. Move the key to the ul
:
{props.food.map((menu) => (
<ul key={menu.id}>
<li className={classes.name}>
{menu.name}
</li>
<li className={classes.info}>{menu.info}</li>
<li className={classes.price}>{menu.price}$</li>
<Button> Add</Button>
</ul>
))}