I'm having a really hard time coming up with a key it gives me an error and I can't figure it out. I've tried giving the unique id to the div with the class artist here's what one data object that's being displayed looks like:
{
id: 1,
title: "Hypervenom Phinish 'Volt'",
price: "200",
SizinginNumbers: true,
img: "https://image.goat.com/transform/v1/attachments/product_template_pictures/images/013/255/557/original/749901_703.png.png?action=crop&width=950",
color: "#cfeb30",
size: null,
itemcolor: null,
catagory: "soccer",
quantity:1
},
this is the where the data is being mapped out the cart is is a state that im using to store the data in.
<div className="cart">
<h1>your Cart </h1>
<h3>you have :{cart.length} item(s) </h3>
{
cart.map((item) => {
return (
<>
<ul className="cartlist" style={{backgroundColor:item.color}}>
<li className="cartitem">x</li>
<li className="cartitem">
<img className="cartimgs" src={item.img} alt="" />
</li>
<li className="cartitem">{item.title}</li>
<li className="cartitem">Size: {item.size}</li>
<li className="cartitem">price: ${item.price}</li>
<button className="quantitybtn">-</button>
<span>{item.quantity}</span>
<button className="quantitybtn"> </button>
</ul>
</>
);
})}
</div>
CodePudding user response:
Just add a key prop to your component (HTML), <></> don't support key or any other attribute to it as prop, so use React.fragment
<div className="cart">
<h1>your Cart </h1>
<h3>you have :{cart.length} item(s) </h3>
{
cart.map((item) => {
return (
<React.fragment key={index}>
<ul className="cartlist" style={{backgroundColor:item.color}}>
<li className="cartitem">x</li>
<li className="cartitem">
<img className="cartimgs" src={item.img} alt="" />
</li>
<li className="cartitem">{item.title}</li>
<li className="cartitem">Size: {item.size}</li>
<li className="cartitem">price: ${item.price}</li>
<button className="quantitybtn">-</button>
<span>{item.quantity}</span>
<button className="quantitybtn"> </button>
</ul>
</React.fragment>
);
})}
</div>
CodePudding user response:
It's very simple just remove react fragment and add key to ul element. If you don't have unique id, map function have index in second parameter.
<div className="cart">
<h1>your Cart </h1>
<h3>you have :{cart.length} item(s) </h3>
{
cart.map((item, index) => {
return (
<ul key={index} className="cartlist" style={{backgroundColor:item.color}}>
<li className="cartitem">x</li>
<li className="cartitem">
<img className="cartimgs" src={item.img} alt="" />
</li>
<li className="cartitem">{item.title}</li>
<li className="cartitem">Size: {item.size}</li>
<li className="cartitem">price: ${item.price}</li>
<button className="quantitybtn">-</button>
<span>{item.quantity}</span>
<button className="quantitybtn"> </button>
</ul>
);
})}
</div>