Home  >  Q&A  >  body text

How to select multiple checkboxes in Reactjs

I have an option list in which I want to select multiple checkboxes but am unable to do so, what is wrong with this code?

Sandbox URL

P粉950128819P粉950128819168 days ago393

reply all(1)I'll reply

  • P粉545218185

    P粉5452181852024-04-07 09:07:36

    According to your requirements, you can change handleCheckboxQuestionInput to:

    const handleCheckboxQuestionInput = (e) => {
        const answer = e.target.value;
        setSelectedAnswers((prevAnswers) => {
          if(prevAnswers.includes(answer)) {
            return prevAnswers.filter(e => e !== answer)
          } else {
            return [...prevAnswers, answer]
          }
        });
      };

    and change at the input element to:

     handleCheckboxQuestionInput(e)}
     />

    Hope it helps you

    reply
    0
  • Cancelreply