I have a small react project which contains a form, I am trying to get multiple values from a checkbox, but everytime i click an item (checkbox) for the first time, it starts out as null, then when i click the another item, It stores the first Item. I would like to store multiple Items from a checkbox. Here is the code below.
import { useState } from "react";
const Toppings = () => {
const [toppings, setToppings] = useState(null)
const [toppingsArray, setToppingsArray] = useState([])
function handleCheck(event) {
if (event.target.checked) {
setToppings({
"type": event.target.id,
"price": event.target.value
})
console.log("toppings: ", toppings)
toppingsArray.push(toppings)
setToppingsArray([toppings])
console.log("toppings array: ", toppingsArray)
}
}
return (
<>
<h2>you can select multiple</h2>
<form>
<label htmlFor="pepperoni">
<input onChange={handleCheck} type="checkbox" name="pepperoni" id="pepperoni" value={300} />
pepperoni
</label>
<label htmlFor="cheese">
<input onChange={handleCheck} type="checkbox" name="cheese" id="cheese" value={200} />
cheese
</label>
<label htmlFor="onions">
<input onChange={handleCheck} type="checkbox" name="onions" id="onions" value={100} />
onions
</label>
</form>
<p>you have selected {JSON.stringify(toppings)}</p>
<p>you have {JSON.stringify(toppingsArray)}</p>
</>
)
}
export default Toppings[enter image description here][1];