so I managed to add the product from ProductDescriptionPage to Cart but without it’s selected attributes(which are radio buttons inputs btw). So do you have any ideea how to add them with the selected attributes and to display them in the Cart component with the same atrributes selected. Do I have to use forms ?
addProduct = (product) => {
this.setState({
cart: [...this.state.cart, product],
cartItems: this.state.cartItems + 1
})
console.log(this.state.cartItems);
}
<div className="details">
<h1 className='name'>{product.name}</h1>
{product.attributes.length > 0 &&
<>
{product.attributes.map((attribute, i) => {
return (
<>
<p className='attributeBold' key={attribute}>
{attribute.name}:
</p>
<ul className={`attributesList ${attribute.id}`} key={attribute.id}>
{product.attributes[i].items.map((item) => {
return (
<li>
<input type="radio" id={`attribute ${item.id}`} name={`attributesList ${attribute.id}`} key={item.id} value={item.displayValue}/>
<label className={`attribute ${item.id}`} style={{backgroundColor: item.value}} for={`attribute ${item.id}`}>{item.displayValue}</label>
</li>
)
})}
</ul>
</>
)
})}
</>
}
<div className="price">PRICE
<p className='priceAmount'><span className='priceSymbol'>{product.prices[0].currency.symbol}</span>{product.prices[0].amount}</p>
</div>
<button className="addToCart" onClick={() => this.props.data.addProduct(product)}>ADD TO CART</button>
When state is updated using its previous value, the callback argument should be used. This is due to the asynchronous nature of state updates.
See https://reactjs.org/docs/state-and-lifecycle.html#state-updates-may-be-asynchronous
It should be:
this.setState((state)=>({
cart: state.cart.concat( state.currentProduct)
}));
To set attributes for the product, make currentProdcut a part of the state. Reset it to null when it's added to the cart.
For each of the attributes, create a radio button with a corresponding onChange listener. In the listener (after binding this) call setState to update the currentProduct.
Eg for color:
Inside render,
['red','blue','green','yellow'].map((color,i)=> (
<>
<input type="radio" onChange={this.handleColorChange} id={color} value={color} />
<label htmlFor={color}>{color}</label>
</>
})
handleColorChange = (evt)=> {
this.setState((state)=>(
var {currentProduct} = state;
currentProduct.color = evt.target.value;
return currentProduct;
});
}
Repeat similarly for other attributes.