I wrote a Checkbox component, with React, that is reused to generate a list of checkboxes. I know that a react element is different from a DOM in terms of state. But how do I check if at least 1 checkbox has been selected by the user on form submit in React?
I have searched in SO and Google but all examples are either in jQuery or vanilla JS. For my case I want a React example.
const Checkbox = ({ title, options, id, name, onChange }) => {
return (
<div className="checkbox-group">
<h4>{title}</h4>
{options.map(option => (
<label htmlFor={`${name}-${index}`} key={`${name}-${index}`}>
<input
type="checkbox"
name={name}
value={option}
onChange={onChange}
id={`${name}-${index}`}
/>
<span> {option}</span>
</label>
))}
</div>
);
};
class Form extends Component {
...
handleChange(event) {
let newSelection = event.target.value;
let newSelectionArray;
newSelectionArray = [
...this.state.sureveyResponses.newAnswers,
newSelection,
];
this.setState(prevState => {
return {
surveyResponse: {
...this.state.surveyResponse,
newAnswers: newSelectionArray,
}
)
}
handleSubmit() {
// I'm guessing this doesn't work in React as it's using its own state!
let checkboxes = document.querySelectorAll('[name="quiz-0"]:checked');
for (let chk in checkboxes) {
if (chk.checked) {
return true;
}
}
alert('Please choose at least one answer.');
return false;
}
render() {
return (
<form onSubmit={this.handleSubmit}>
<h4>Choose</>
{this.state.surveyQuiz.map((quiz, index) => {
return (
<div key={index}>
<Checkbox
title={quiz.question}
options={quiz.answers}
name={`quiz-${index + 1}`}
onChange={this.handleChange}
/>
</div>
);
})};
<button>Save answer(s)</span>
</form>
);
}
}
When the user submits the form, it should check if at least a checkbox is checked, if not none is checked then prevent the form to submit, i.e. return false!
You should also maintain the checked property in surveyResponse.newAnswers state. Then, you'll be able to check if any of them is true. For eg.:
const nA = this.state.surveyResponse.newAnswers
const isChecked = nA.some(c => c.checked == true)
if(isChecked) {
//...if any of them has checked state
}
Assuming example newAnswers data:
[
{answer:'foo', checked: false},
{answer:'bar', checked: true},
...
]
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With