mercredi 27 mars 2019

In React how do you check if at least one checkbox has been selected

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?

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.

component

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!




Aucun commentaire:

Enregistrer un commentaire