I am trying to have a single button that will add the value to the array, or if the value already exists in the array to remove that value.
The array is called toppings
const ToppingPlusMinus = (e) => {
if (toppings.includes(e.target.value, 1)) {
removeTopping(e)
}
else {
changeToppings(e);
}
}
The two functions
const removeTopping = (e) => {
toppings.splice(e.target.value)
}
const changeToppings = (e) => {
setToppings([...toppings, e.target.value]);
};
The buttons are toppings on a pizza, and they are in this format
<button
type="button"
value="Sausage, "
className="button btn first"
onClick={(event) => {
ToppingPlusMinus(event);
}}
>
Sausage
</button>
This works fine for adding the value to the array, however on removal there are unexpected outcomes.
- the item only is removed after the user double clicks the button
- the removal also removes the topping before it in the array.
- the button does not stay in its active state while the item is in the array (I haven't attempted this, but if anyone know how to do it I'd be appreciative)
I have set up a codesandbox with my code here
I appreciate your help.