mardi 30 novembre 2021

How to fill array of boolean values on checkbox change event?

What I would like to do is, filling the answers array with boolean values.My checkboxes are populated dynamically but there will be only four of them. If checkbox is unchecked then its value should be false and if checked it should be true.Values should correspond to array index, I mean if first checkbox is switched then only answers[0] should change, if second checkbox is changed then answers[1] and so on..

I would also appreciate if you can help me setting the checked value as well.

In the end I am setting this values to the context store to be send to server in the end.

const Quiz1 = (props) => {
      const [answers, setAnswers] = useState([false, false, false, false]);

  const handleChange = (e) => {
     setAnswers([...answers, e.target.checked]);
     setQuizState({ id: 0, question_id: question.question_id, answer: [answers] });
  };
    return (
    {question?.options?.map((option, i) => { 
       <Checkbox
         id={i}
         name={option}
         checked={WHAT TO PUT HERE?}
         onChange={(e) => handleChange(e)}
      />}
 )
}



Aucun commentaire:

Enregistrer un commentaire