Why am I having this kind of warning every time I'll a product "Warning: Encountered two children with the same key"?

Warning:

Warning: Encountered two children with the same key

How can I fix this warning?

Code for adding the product:

const handleAdd = (id, name, price, size, cat, color) => {
    console.log("add", id, name, price, size, cat, color);
    const productExist = cartItems.find(
      (item) => item.id === id && item.color === color
    );

    if (productExist) {
      setCartItems(
        cartItems.map((item) =>
          item.id === id && item.color === color
            ? { ...productExist, quantity: productExist.quantity + 1 }
            : item
        )
      );
    } else {
      setCartItems([
        ...cartItems,
        { id, name, price, size, cat, color, quantity: 1 }
      ]);
    }
  };

Codesandbox: Add to Cart Sampled 2 with Table - CodeSandbox

aRLMZkiSU7T0lcsPCSsV <--- id
Tumbler 500ML
Black
1
Total: 200

aRLMZkiSU7T0lcsPCSsV <--- id
Tumbler 500ML
Pink
1
Total: 200

You see that those two items have the same id?

Hi Aranya

I looked over your app, pretty cool shopping cart your working on.

I see the root of the issue, it’s in the Cart.js file.

When react loops over an array, it likes a unique key for each item rendered to the dom.

Your component uses item id’s as the key. However different colors of the same item share the same key.

So you need to create unique id’s for each variation of each item so every unique item has a unique key.

For example when you add a Green Tumbler, it has an id of "aRLMZkiSU7T0lcsPCSsV", and when a Pink tumbler is added, it also has an id of "aRLMZkiSU7T0lcsPCSsV". These are two separate items being written to the dom and they share the same key. If these two items had unique id’s you’d be fine.

This is only acceptable for the static arrays where items are not added/removed which is not the case here.

What are other solutions that I could do since I also need to store the id of each of the products?

Right, are there any other solution since I would need to store the product ID as well?

I’ve actually edited it this part to take index


{searchList.map((item, index) => (
            <List key={index}>

But yes, there’s still a warning

For example id + color.

2 Likes

Jenovs suggested a good solution.

I believe the error your still seeing is because there’s another .map in App.js on line 144 that isn’t using keys properly.

1 Like

Thank you for the help. I added this for the key for both the App.js and Cart.js

<List key={item.id + item.color}>

1 Like

Thank you for the help as well

This topic was automatically closed 182 days after the last reply. New replies are no longer allowed.