Reputation: 1
I'm trying to check if a checkbox component is checked within a state hook method of a Material-UI Checkbox, I've searched a lot but none of the solutions worked for me.
The end goal is to add a new object into the state if the checkbox is checked and remove an object from the state if the checkbox is unchecked while the equivalent object is present in the state.
My current code is adding new items into the state regardless the Checkbox is checked or unchecked, and am looking for a simple way to update my state accordingly.
My code:
const multiSelectQuestions = currQuestion.answerOptions.map(
({ answerText, price }) =>
answerText !== "Custom" ? (
<FormControlLabel
className="currentCheckbox"
value={answerText}
control={<Checkbox />}
label={answerText}
price={price}
onChange={() =>
updateSelectedCheckboxes([
...selectedCheckboxes,
{
selectedAnswer: answerText,
price: price,
},
])
}
/>
) : (
<div className="customOption">
<FormControlLabel
value={answerText}
control={<Checkbox />}
label={answerText}
price={price}
/>
<TextField
label="Please Specify"
variant="outlined"
id="mui-theme-provider-outlined-input"
/* error */
/>
</div>
)
);
Upvotes: 0
Views: 4755
Reputation: 504
Try changing from this:
onChange={() =>
updateSelectedCheckboxes([
...selectedCheckboxes,
{
selectedAnswer: answerText,
price: price,
},
])
}
to this:
onChange={(event) =>
updateSelectedCheckboxes([
...selectedCheckboxes,
{
selectedAnswer: answerText,
price: price,
},
])
}
then you can get the value of the checkbox like this:
event.target.checked
Upvotes: 1