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

113
Visualizações
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 Respostas
Responde à pergunta

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 Relatório

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 Relatório

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