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?
CodePudding user response:
- First you need to call onSubmit on the
form
element. - 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
CodePudding user response:
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) => this.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){
this.setState({
score : this.state.score 1,
})
}
}