Recently, I've been facing an issue with changing the color of an item after it has been added to the cart. Below are my functions for adding and removing items from the cart:
function addToCart(newItem) {
cartItems.map(item => newItem.type === item.type && removeFromCart(item))
setCartItems(prevItems => [...prevItems, newItem])
}
function removeFromCart(itemToRemove) {
setCartItems(prevItems => prevItems.filter(item =>
`${item.id}-${item.type}` !== `${itemToRemove.id}-${itemToRemove.type}`))
}
I have a component called 'Option' which displays each service within its structure:
const serviceElements = servicesList.map(service =>
<Service key={service.id}
id={service.id}
name={service.name}
type={service.type}
/> )
return (
<div className={`Options-${context.theme}`} >
<ul>
{serviceElements}
</ul>
</div>
)
This is how the 'Service' component looks like:
<>
<li onClick={() => { context.cartItems.includes(props)
? context.removeFromCart(props)
: context.addToCart(props)}}>
{props.name}
</li>
</>
My attempt at adding a class to the 'Service' component resulted in all elements in the displayed list changing color, instead of just the specific one I wanted to change:
<>
<li
className={context.cartItems.includes(props) ? "notInCart" : "inCart"}
onClick={() => { context.cartItems.includes(props)
? context.removeFromCart(props)
: context.addToCart(props)}}>
{props.name}
</li>
</>
I have experimented with different styling options in my SCSS file but cannot pinpoint the exact source of the problem:
.Options-light {
@extend .TimeGrid-light;
ul {
.inCart {
background-color: blue;
}
.notInCart {
background-color: red;
}
}
}
//and also tried
.Options-light {
@extend .TimeGrid-light;
.inCart {
background-color: blue;
}
.notInCart {
background-color: red;
}
}
It's challenging to identify where the issue lies exactly.