when i add product in cart there is nothing displayed in car and "items not found" error is displayed on the screen and when i try to use null check and npm start then error is not shown but still balnk page is displayed.
import React from 'react';
import Header from './Front/Header/Header';
const Cart = ({ cartitems ,handleAddProduct,handleRemoveProduct} ) => {
return (
<>
<Header />
<div className="cart-items">
<div className="cart-items-header"> cartitems</div>
{!cartitems?.length ? (
<div className="cart-items-empty"> No items added in cart</div>
) : null}
<div>
{cartitems?.length ? cartitems.map((item,name ,price ,image ,id) => (
<img
key={item.id}
className="cart-items-image"
src={item.image}
alt={item.name}
/>
)) : null}
</div>
<div>
<h3 className='cart-items-name'>
{item.name}</h3>
</div>
<div className='cart-items-function'>
<button className='cart-items-add' onClick={() =>handleAddProduct(item)}>
+
</button>
<button
className='cart-items-remove' onClick={()=>handleRemoveProduct(item)}>
-
</button>
</div>
<div
className='cart-items-price'>
{item.quantity}* ${item.price}
</div>
</div>
</>
);
}
export default Cart;
I think there are 2 problems in your code :
Firstly, I suppose that each item in your cartitems has the following structure :
item = { id: 1, name: "my item", price: 2, image: "http://mybeautifulurl.org/image.png" }
If that is the case, you should pass item as the only argument in the map function, and access each props with item.id, item.name, item.price and item.image.
map function but needs the item, so it cannot display anything.Here is your updated code :
import React from "react";
import Header from "./Front/Header/Header";
const Cart = ({ cartitems, handleAddProduct, handleRemoveProduct }) => {
return (
<>
<Header />
<div className="cart-items">
<div className="cart-items-header"> cartitems</div>
{!cartitems?.length ? (
<div className="cart-items-empty"> No items added in cart</div>
) : null}
<div>
{cartitems?.length
? cartitems.map((item) => (
<>
<img
key={item.id}
className="cart-items-image"
src={item.image}
alt={item.name}
/>
<div>
<h3 className="cart-items-name">{item.name}</h3>
</div>
<div className="cart-items-function">
<button
className="cart-items-add"
onClick={() => handleAddProduct(item)}
>
+
</button>
<button
className="cart-items-remove"
onClick={() => handleRemoveProduct(item)}
>
-
</button>
</div>
<div className="cart-items-price">
{item.quantity}* ${item.price}
</div>
</>
))
: null}
</div>
</div>
</>
);
};
export default Cart;
Let me know if this solves the problem :)