11 - Simple Quiz App with Multiple Choice
Description
Algorithm
Classes
Code
import React, { useState } from 'react';
function QuizApp() {
const [questions, setQuestions] = useState([...]); // array of questions
const [currentIndex, setCurrentIndex] = useState(0);
const [score, setScore] = useState(0);
const [selectedAnswer, setSelectedAnswer] = useState('');
const handleAnswerSelection = (answer) => {
setSelectedAnswer(answer);
if (answer === questions[currentIndex].correctAnswer) {
setScore(score + 1);
}
};
const proceedToNextQuestion = () => {
setCurrentIndex(currentIndex + 1);
};
return (
<div>
{currentIndex < questions.length ? (
<div>
<p>{questions[currentIndex].question}</p>
<ul>
{questions[currentIndex].options.map((option) => (
<li key={option}>
<input
type="radio"
name="answer"
value={option}
checked={selectedAnswer === option}
onChange={() => handleAnswerSelection(option)}
/>
<span>{option}</span>
</li>
))}
</ul>
<button onClick={proceedToNextQuestion}>Next Question</button>
<p>Score: {score}</p>
</div>
) : (
<div>
<p>Quiz submitted!</p>
<p>Final Score: {score}</p>
</div>
)}
</div>
);
}
export default QuizApp;
Explanation
Possible Future Enhancements
Last updated