简体   繁体   中英

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..

Sandboxhttps://codesandbox.io/s/elated-thompson-7rthy?file=/src/App.js

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)}
      />}
 )
}

You can make a shallow copy of the state and change its value. Here's the simple sample of the thing which you want:

import { useEffect, useState } from "react";

const Quiz1 = (props) => {
  const question = {
    options: ["1", "2", "3", "4"]
  };

  const [answers, setAnswers] = useState([false, false, false, false]);

  useEffect(() => {
    console.log(answers);
  }, [answers]);

  const handleChange = (e, i) => {
    let copy = [...answers];
    let current = copy[i];
    current = e.target.checked;
    copy[i] = current;
    setAnswers(copy);
  };
  return question?.options?.map((option, i) => {
    return (
      <>
        <label>{option}</label>
        <input
          aria-label={option}
          id={i}
          name={option}
          checked={answers[i]}
          type="checkbox"
          onChange={(e) => handleChange(e, i)}
        />
      </>
    );
  });
};
export default function App() {
  return <Quiz1 />;
}

编辑挥之不去的共振7mycm

If I understand you correctly, you can just use the index of your map function to use the correct answer index.

checked={answer[i]}

Setting setAnswers([...answers, e.target.checked]) will append the new new event value to your answer array. Instead you should override the answer value.

answer[i] = e.target.value

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM