Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

121
Visualizações
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..

Sandbox https://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)}
      />}
 )
}
about 4 years ago · Juan Pablo Isaza
2 Respostas
Responde à pergunta

0

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

Edit lingering-resonance-7mycm

about 4 years ago · Juan Pablo Isaza Relatório

0

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

about 4 years ago · Juan Pablo Isaza Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda