'How can I show the data of the cartItems by their id?

I have these cart items where there could be the same products with multiple colors in the cart. Like this: enter image description here

How can I display it where it will display the product name, size, and category once, then below it are the different colors along with their quantity. Something like this:

  • Product ID
  • Tumbler 500 ML
  • Green : 4 (button to add and remove product) and the total
  • Pink : 5 (button to add and remove product) and the total
  • Black: 6 (button to add and remove product) and the total

Any help would be appreciated. Thank you.

Codesandbox: https://codesandbox.io/s/add-to-cart-sampled-2-efqrhd?file=/src/Cart.js:67-1764

const Cart = ({ cartItems, handleCartClearance, handleRemove, handleAdd }) => {
  console.log(cartItems, "items");

  const totalAmount = cartItems.reduce(
    (price, item) => price + item.quantity * item.price,
    0
  );

  const handleSubmit = (e) => {
    e.preventDefault();
    console.log(cartItems, "order");
  };

  return (
    <div>
      <form onSubmit={handleSubmit}>
        Order page
        {cartItems.length >= 1 && (
          <Button onClick={handleCartClearance}>Clear Orders</Button>
        )}
        {cartItems.length === 0 && <div>No Items in the cart</div>}
        <div>
          {cartItems.map((item) => (
            <div key={item.id + item.color}>
              <li>{item.id}</li>
              <li>{item.name + " " + item.size + "" + item.cat}</li>
              <li>{item.color}</li>
              <li>{item.quantity}</li>

              <li>Total: {Number(item.quantity) * Number(item.price)}</li>
              <button
                onClick={(e) =>
                  handleAdd(
                    item.id,
                    item.prodName,
                    item.price,
                    item.size,
                    item.cat,
                    item.color
                  )
                }
              >
                +
              </button>
              <button onClick={() => handleRemove(item)}>- </button>
            </div>
          ))}
          -----------------------------------------------------
          <div>
            <b>Total Amount :{totalAmount}</b>
          </div>
          {cartItems.length >= 1 && <Button type="submit">Save Order</Button>}
        </div>
      </form>
    </div>
  );
};

export default Cart;


Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source