Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

120
Vistas
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 Respuestas
Responde la pregunta

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 Denunciar

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 Denunciar
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda