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

111
Vistas
How to submit a form with radio buttons in react and increment the state by one based on the value submitted?

I am working on a quiz app in React and I have created some functionality of showing the question and answers and also the functionality to select the radio buttons as answers. However, the problem that I am facing is that I don't know how to submit the form and get the value of the radio button selected, and then increment the score by 1 if the selected answer is correct.

Here is my JSX:

 <form className="answer_div">
      {questions[currentQuestion].answerOptions.map(
          (answerOption) => (
              <div>
                  <input
                  type="radio"
                  value={answerOption.answerText}
                  name={"answerOption"}
                  >answerOption.answerText}
              </div>
          )
          )}
         <input type="submit" value="Submit" onSubmit={handleFormSubmit} />
</form>

I am rendering the question and answers from a js object which looks like this:

export const questions = [
{
    questionText:
        "who is the ceo of tesla:",
    answerOptions: [
        {
            answerText: "elon musk",
            isCorrect: false,
        },
        {
            answerText:
                "jeff bezos",
            isCorrect: true,
        },
        {
            answerText:
                "sundar pichai",
            isCorrect: false,
        },
        {
            answerText: "tom cruise.",
            isCorrect: false,
        },
    ],
},

];

I want to increment the score by 1 if the isCorrect is true

here is the state that I want to increment by 1 if the value of the submitted answer is correct:

 const [score, setScore] = useState(0);

How can I achieve the above functionality?

about 4 years ago · Juan Pablo Isaza
3 Respuestas
Responde la pregunta

0

  1. First you need to call onSubmit on the form element.
  2. Then you need to store the value of the selected checkbox and for that you can use a state or some

If you use a state, you can store the checkbox position (answer) in the state and use the checked attribute of the input (checkbox) to compare the index with the state.

see an example: https://codesandbox.io/s/pedantic-oskar-ouov3e?file=/src/App.js:701-1196

about 4 years ago · Juan Pablo Isaza Denunciar

0

This is what you can do:

Step 1 : Add onChange attribute to the radio input tag, And "onChange" run the function handleCorrect .

<div>
    <input
     type="radio"
     value={answerOption.answerText}
     name={"answerOption"}
     onChange={(e) => handleCorrect(answerOption, e)}
    />{answerOption.answerText}
 </div>

Step 2: Now in the handleCorrect function you can save answer in a global variable or as in the state.

handleCorrect = (a,e) => {
        if(e.target.checked){
              answer = a;
        }
        console.log(e.target.checked, a);
    }

Step 3: Then in the handleFormSubmit function you can check whether the answer was correct and increment the score.

handleFormSubmit = () =>{
    if(answer.isCorrect){
        setScore(score+1);
    }
}
about 4 years ago · Juan Pablo Isaza Denunciar

0

Change value of isCorrect true false on change of radio option.

On Form submit, get and check if isCorrect value is true then increase score by one else 0.

const [isCorrect, setIsCorrect] = useState(false);
const [score, setScore] = useState(0);
return <form className="answer_div" onSubmit={e => { e.preventDefault(); setScore(isCorrect === "true" ? 1 : 0); }}>
    {questions[currentQuestion].answerOptions.map((answerOption, index) => (
        <div key={index}>
            <input type="radio" name="answerOption" value={answerOption.isCorrect} onChange={e => setIsCorrect(e.target.value)} /> {answerOption.answerText}
        </div>
    ))}
    <input type="submit" value="Submit" />
</form>
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