Project: "Interactive Quiz App"
by Andrew Nguyenยท Module 05: Handling Events

Introduction
Not Attempted
NameProgress
Course outline
Not Read
Module 01 - Diving Into React
Not Attempted
NameProgress
Key Concepts
Not Read
Project: Pet Parade
Not Read
Challenge 1
Not Attempted
Quiz 1
Not Attempted
Module 02 - Components and Props
Not Attempted
NameProgress
Project: Profile Card Creator
Not Read
Key Concepts
Not Read
Challenge 2
Not Attempted
Quiz 2
Not Attempted
Module 03 - State and Effect
Not Attempted
NameProgress
Key Concepts
Not Read
Project: Magic Garden
Not Read
Challenge 3
Not Attempted
Quiz 3
Not Attempted
Module 04 - Conditional Rendering
Not Attempted
NameProgress
Key Concepts
Not Read
Project: Weather Wardrobe
Not Read
Challenge 4
Not Attempted
Quiz 4
Not Attempted
Key Concepts
Project: "Interactive Quiz App"
Challenge 5
Not Attempted
Quiz 5
Not Attempted
Module 06 - Lists and Keys
Not Attempted
NameProgress
Key Concepts
Not Read
Project: "Photo Gallery"
Not Read
Challenge 6
Not Attempted
Quiz 6
Not Attempted
Module 07 - Forms and Validation
Not Attempted
NameProgress
Key Concepts
Not Read
Project: "Registration Form"
Not Read
Challenge 7
Not Read
Quiz 7
Not Attempted
Module 08 - Lifting State Up & Composition vs Inheritance
Not Attempted
NameProgress
Key Concepts
Not Read
Project: "Weather Dashboard"
Not Read
Challenge 8
Not Attempted
Quiz 8
Not Attempted
0 / 470 XP

Objective: Create a quiz application where users can select answers and get immediate feedback.

Description: In this project, you will build a simple interactive quiz application. Users will select answers to quiz questions and receive immediate feedback on whether their choice was correct or incorrect. This project will help you practice handling events and using controlled components in React.

Instructions:

Step 1: Setup Your Project

  • Create a new React project using Vite.
  • Set up your project structure with a main <strong>App</strong> component and a <strong>Quiz</strong> component.

Step 2: Define the Quiz Questions and Answers

Create a state to store the quiz questions, answers, and the user's current selection.

import React, { useState } from 'react';

function Quiz() {
  const questions = [
    {
      question: "What is the capital of France?",
      options: ["Berlin", "Madrid", "Paris", "Rome"],
      answer: "Paris"
    },
    {
      question: "What is 2 + 2?",
      options: ["3", "4", "5", "6"],
      answer: "4"
    }
  ];

  const [currentQuestionIndex, setCurrentQuestionIndex] = useState(0);
  const [selectedOption, setSelectedOption] = useState('');
  const [feedback, setFeedback] = useState('');

  return (
    &lt;div&gt;
      {/* Render question and options here */}
    &lt;/div&gt;
  );
}

export default Quiz;

Step 3: Render the Quiz Questions and Options

Render the current quiz question and its options as radio buttons. Allow the user to select an option.

return (
  &lt;div&gt;
    &lt;h2&gt;{questions[currentQuestionIndex].question}&lt;/h2&gt;
    &lt;form&gt;
      {questions[currentQuestionIndex].options.map((option, index) =&gt; (
        &lt;div key={index}&gt;
          &lt;label&gt;
            &lt;input
              type="radio"
              value={option}
              checked={selectedOption === option}
              onChange={(e) =&gt; setSelectedOption(e.target.value)}
            /&gt;
            {option}
          &lt;/label&gt;
        &lt;/div&gt;
      ))}
    &lt;/form&gt;
    {/* Render feedback and navigation buttons here */}
  &lt;/div&gt;
);

Step 4: Handle User Selection and Provide Feedback

Create a function to handle the user's answer submission and provide immediate feedback.

function handleSubmit(event) {
  event.preventDefault();
  const correctAnswer = questions[currentQuestionIndex].answer;
  if (selectedOption === correctAnswer) {
    setFeedback('Correct!');
  } else {
    setFeedback('Incorrect, try again.');
  }
}

return (
  &lt;div&gt;
    &lt;h2&gt;{questions[currentQuestionIndex].question}&lt;/h2&gt;
    &lt;form onSubmit={handleSubmit}&gt;
      {questions[currentQuestionIndex].options.map((option, index) =&gt; (
        &lt;div key={index}&gt;
          &lt;label&gt;
            &lt;input
              type="radio"
              value={option}
              checked={selectedOption === option}
              onChange={(e) =&gt; setSelectedOption(e.target.value)}
            /&gt;
            {option}
          &lt;/label&gt;
        &lt;/div&gt;
      ))}
      &lt;button type="submit"&gt;Submit&lt;/button&gt;
    &lt;/form&gt;
    &lt;p&gt;{feedback}&lt;/p&gt;
    {/* Render navigation buttons here */}
  &lt;/div&gt;
);

Step 5: Add Navigation Between Questions

Implement navigation to move between questions and reset the feedback and selected option for each new question.

function handleNextQuestion() {
  setCurrentQuestionIndex((prevIndex) =&gt; (prevIndex + 1) % questions.length);
  setSelectedOption('');
  setFeedback('');
}

return (
  &lt;div&gt;
    &lt;h2&gt;{questions[currentQuestionIndex].question}&lt;/h2&gt;
    &lt;form onSubmit={handleSubmit}&gt;
      {questions[currentQuestionIndex].options.map((option, index) =&gt; (
        &lt;div key={index}&gt;
          &lt;label&gt;
            &lt;input
              type="radio"
              value={option}
              checked={selectedOption === option}
              onChange={(e) =&gt; setSelectedOption(e.target.value)}
            /&gt;
            {option}
          &lt;/label&gt;
        &lt;/div&gt;
      ))}
      &lt;button type="submit"&gt;Submit&lt;/button&gt;
    &lt;/form&gt;
    &lt;p&gt;{feedback}&lt;/p&gt;
    &lt;button onClick={handleNextQuestion}&gt;Next Question&lt;/button&gt;
  &lt;/div&gt;
);

Step 6: Styling and Enhancements

Add some basic CSS to style your quiz application and make it visually appealing.

/* Add to your Quiz.css file */
.quiz {
  text-align: center;
  font-family: Arial, sans-serif;
}

button {
  background-color: #007bff;
  color: white;
  padding: 10px 20px;
  border: none;
  border-radius: 5px;
  cursor: pointer;
  margin: 5px;
}

button:hover {
  background-color: #0056b3;
}

form {
  display: inline-block;
  text-align: left;
}

Example Code: Complete Quiz Component

import React, { useState } from 'react';
import './Quiz.css';

function Quiz() {
  const questions = [
    {
      question: "What is the capital of France?",
      options: ["Berlin", "Madrid", "Paris", "Rome"],
      answer: "Paris"
    },
    {
      question: "What is 2 + 2?",
      options: ["3", "4", "5", "6"],
      answer: "4"
    }
  ];

  const [currentQuestionIndex, setCurrentQuestionIndex] = useState(0);
  const [selectedOption, setSelectedOption] = useState('');
  const [feedback, setFeedback] = useState('');

  function handleSubmit(event) {
    event.preventDefault();
    const correctAnswer = questions[currentQuestionIndex].answer;
    if (selectedOption === correctAnswer) {
      setFeedback('Correct!');
    } else {
      setFeedback('Incorrect, try again.');
    }
  }

  function handleNextQuestion() {
    setCurrentQuestionIndex((prevIndex) =&gt; (prevIndex + 1) % questions.length);
    setSelectedOption('');
    setFeedback('');
  }

  return (
    &lt;div className="quiz"&gt;
      &lt;h2&gt;{questions[currentQuestionIndex].question}&lt;/h2&gt;
      &lt;form onSubmit={handleSubmit}&gt;
        {questions[currentQuestionIndex].options.map((option, index) =&gt; (
          &lt;div key={index}&gt;
            &lt;label&gt;
              &lt;input
                type="radio"
                value={option}
                checked={selectedOption === option}
                onChange={(e) =&gt; setSelectedOption(e.target.value)}
              /&gt;
              {option}
            &lt;/label&gt;
          &lt;/div&gt;
        ))}
        &lt;button type="submit"&gt;Submit&lt;/button&gt;
      &lt;/form&gt;
      &lt;p&gt;{feedback}&lt;/p&gt;
      &lt;button onClick={handleNextQuestion}&gt;Next Question&lt;/button&gt;
    &lt;/div&gt;
  );
}

export default Quiz;

By completing this project, you'll gain hands-on experience with handling events in React, making your applications interactive and responsive to user inputs. Enjoy building your Interactive Quiz App and watching it come to life!

Maggie

Discuss with Maggie
Use the power of generative AI to interact with course content

Discussion

0 comments
Loading editor ...
Remember to be polite and report any undesirable behaviour

Category

Empty

Labels

Discussion has no labels

1 participant

user avatar

Priority

Notifications

You're not receiving notifications from this thread.
Course Outline