11 - Simple Quiz App with Multiple Choice

Description

Develop a web application featuring a basic quiz where users can:

  • View questions one at a time.

  • Choose from multiple choice answers for each question.

  • Submit their answer and receive immediate feedback (correct/incorrect).

  • Track their progress and see their final score after completing the quiz.

Algorithm

  1. Data Structure:

    • Store an array of quiz objects, each containing:

      • Question text

      • Array of answer choices (one correct, others incorrect)

    • Track user answers in an array or object alongside the corresponding question index.

  2. User Interface:

    • Display one question at a time with its text and answer choices.

    • Implement radio buttons or checkbox buttons for answer selection.

    • Provide a "Submit Answer" button to register user choice.

    • Show feedback (correct/incorrect) after answer submission.

    • Display a progress bar or question number indicator.

    • After all questions are answered, show the final score and option to restart the quiz.

  3. Functionality:

    • Validate user answers upon submission.

    • Update user score based on correct/incorrect answers.

    • Maintain current question index for displaying questions sequentially.

    • Reset state upon quiz completion for restarts.

Code

import React, { useState } from 'react';

const questions = [
  {
    question: 'What is the capital of France?',
    choices: ['London', 'Paris', 'Berlin', 'Madrid'],
    answer: 1,
  },
  // ... more questions
];

function QuizApp() {
  const [currentQuestion, setCurrentQuestion] = useState(0);
  const [userAnswers, setUserAnswers] = useState([]);
  const [score, setScore] = useState(0);

  const handleAnswerSelection = (answerIndex) => {
    setUserAnswers([...userAnswers, answerIndex]);
  };

  const handleSubmitAnswer = () => {
    const isCorrect = userAnswers[currentQuestion] === questions[currentQuestion].answer;
    setScore(isCorrect ? score + 1 : score);
    if (currentQuestion === questions.length - 1) {
      // Show final score and restart option
    } else {
      setCurrentQuestion(currentQuestion + 1);
    }
  };

  const renderQuestion = () => {
    if (currentQuestion >= questions.length) return <p>Quiz completed!</p>;
    const question = questions[currentQuestion];
    return (
      <div>
        <h3>{question.question}</h3>
        {question.choices.map((choice, index) => (
          <label key={index}>
            <input
              type="radio"
              name="answer"
              value={index}
              onChange={() => handleAnswerSelection(index)}
            />
            {choice}
          </label>
        ))}
        <button onClick={handleSubmitAnswer}>Submit Answer</button>
      </div>
    );
  };

  return (
    <div className="quiz-app">
      <h1>Simple Quiz</h1>
      <p>Question {currentQuestion + 1} of {questions.length}</p>
      {renderQuestion()}
      {score > 0 && <p>Your score: {score}/{questions.length}</p>}
    </div>
  );
}

export default QuizApp;

Explanation

  1. Data Structure:

    • questions array: Stores quiz objects containing question text, answer choices, and the correct answer index.

    • currentQuestion state variable: Tracks the current question index.

    • userAnswers state variable: Stores user-selected answers.

    • score state variable: Holds the user's current score.

  2. Functionality:

    • handleAnswerSelection: Updates the userAnswers array with the selected answer index.

    • handleSubmitAnswer:

      • Checks for a correct answer and updates the score.

      • Advances to the next question or displays final score and restart option.

    • renderQuestion: Renders the current question, answer choices, and submit button.

  3. User Interface:

    • Displays the quiz title and progress indicator.

    • Renders the current question and answer choices using radio buttons.

    • Shows a "Submit Answer" button.

    • Displays the score if at least one question has been answered.

    • Shows a "Quiz completed!" message after the last question.

Additional Notes

  • Consider adding a timer for each question to encourage pace.

  • Implement a review section to show correct answers and explanations.

  • Allow users to choose quiz difficulty or categories.

  • Integrate features like user login and leaderboards.

Last updated