How to Make a Quiz App in React

In this article, we will create a Quiz app in React. This Quiz game will usually be like other Quiz games. Here we will have some questions along with 4 options and a scorecard. After answering all questions, the result will appear, and lastly, we will have a button to restart the quiz.

So basically this is going to be a beginner-friendly project, so let’s make this project step-by-step.

Pre-requisites to Make Quiz App in React

  • Basic knowledge of ReactJS.
  • Basic knowledge of React hooks.
  • Basic knowledge of React props.
  • Good knowledge of React Components.

Building Skeleton for Quiz App in React

Let’s start with a little hard code, in the return() statement, for questions, we have added a header tag for the name of the quiz, and then another heading for the score. Then, after we have hard-coded our question and its options in the question card. And then lastly we have added a result card where we have again hard-coded correct answers and a restart button. This is just the beginning of the app, so it is right now hard coded, but we will improve this code after adding CSS.

return (
   <div className="App">
      {/* 1. Header  */}
      <h1>USA Quiz</h1>

      {/* 2. Current Score  */}
      <h2>Score: 0</h2>

      {/* 3. Show results or show the question game  */}
      {/* Final Results */}
      
        {/* 5. Question Card  */ }
        <div className="question-card">
          {/* Current Question  */}
          <h2>
            Question: 2 out of 5
          </h2>
          <h3 className="question-text">What is the capital of America?</h3>

          {/* List of possible answers  */}
          <ul>
            <li>New York City</li>
            <li>Boston</li>
            <li>Santa Fe</li>
            <li>Washington DC</li>
          </ul>
          
        </div>
        <div className="final-results">
          <h1>Final Results</h1>
          <h2>
            1 out of 5 correct - (
            20%)
          </h2>
          <button onClick={() => restartGame()}>Restart game</button>
        </div>
      
    </div>
  );
Quiz App in React

Adding CSS to Quiz App in React

Now, before making it dynamic, let’s add some CSS. We won’t go deeper with CSS because it’s not a big deal for us, nor it’s too hard to understand, so we just copy and paste it.

.App {
  text-align: center;
}

.question-card {
  /* Center the div  */
  margin: 0 auto;

  /* Dimensions  */
  width: 80%; /* Can be in percentage also. */
  height: auto;

  /* Visual  */
  background-color: gray;
  padding: 16px;
  border-radius: 16px;
  color: white;
  box-shadow: rgba(50, 50, 93, 0.25) 0px 30px 60px -12px,
    rgba(0, 0, 0, 0.3) 0px 18px 36px -18px;
}

ul {
  list-style: none;
}

li {
  margin-top: 8px;
  background-color: darkgray;
  padding: 16px;
  border: 3px solid white;
  border-radius: 20px;
  font-size: 20px;
}

.question-text {
  color: darkblue;
  font-size: 24px;
}

/* Final Results  */

.final-results {
  /* Center the div  */
  margin: 0 auto;

  /* Dimensions  */
  width: 50%; /* Can be in percentage also. */
  height: auto;
  margin-top: 64px;

  /* Visual  */
  background-color: gray;
  padding: 16px;
  border-radius: 16px;
  color: white;
  box-shadow: rgba(50, 50, 93, 0.25) 0px 30px 60px -12px,
    rgba(0, 0, 0, 0.3) 0px 18px 36px -18px;
}

button {
  background-color: red; /* Green */
  border: none;
  color: white;
  padding: 16px 24px;
  text-align: center;
  text-decoration: none;
  display: inline-block;
  font-size: 16px;
  font-weight: bold;

  border-radius: 24px;
}
Quiz App in React

Removing Result Part From Questions

Now let’s begin by removing the result part from the question screen, for that we have just added a state showResult with an initial value false. Then we use using ternary condition on the result and question card where if showResult is false then the question card will be visible and if showResult is true then the result card will show up.

const [showResults, setShowResults] = useState(false);


return (
    <div className="App">
       {/* 1. Header  */}
       <h1>USA Quiz</h1>
 
       {/* 2. Current Score  */}
       <h2>Score: 0</h2>
       
       {/* 3. Show results or show the question game  */}
       {/* Final Results */}
       {showResults? (
       <div className="final-results">
           <h1>Final Results</h1>
           <h2>
             1 out of 5 correct - (
             20%)
           </h2>
           <button onClick={() => restartGame()}>Restart game</button>
         </div>
       ) : (
         
         <div className="question-card">
           {/* Current Question  */}
           <h2>
             Question: 2 out of 5
           </h2>
           <h3 className="question-text">What is the capital of America?</h3>
 
           {/* List of possible answers  */}
           <ul>
             <li>New York City</li>
             <li>Boston</li>
             <li>Santa Fe</li>
             <li>Washington DC</li>
           </ul>
           
         </div>
         )}
     </div>
       
  );
Quiz App in React

Adding Questions Data

Now let’s add Questions, we have made a component named Questions.js component, and we have added a questions array in which we have added text property with a question and another property is options where we added 4 options with IDs, and also we have added isCorrect property with boolean values true and false.

const questions = [
    {
      text: "What is the capital of America?",
      options: [
        { id: 0, text: "New York City", isCorrect: false },
        { id: 1, text: "Boston", isCorrect: false },
        { id: 2, text: "Santa Fe", isCorrect: false },
        { id: 3, text: "Washington DC", isCorrect: true },
      ],
    },
    {
      text: "What year was the Constitution of America written?",
      options: [
        { id: 0, text: "1787", isCorrect: true },
        { id: 1, text: "1776", isCorrect: false },
        { id: 2, text: "1774", isCorrect: false },
        { id: 3, text: "1826", isCorrect: false },
      ],
    },
    {
      text: "Who was the second president of the US?",
      options: [
        { id: 0, text: "John Adams", isCorrect: true },
        { id: 1, text: "Paul Revere", isCorrect: false },
        { id: 2, text: "Thomas Jefferson", isCorrect: false },
        { id: 3, text: "Benjamin Franklin", isCorrect: false },
      ],
    },
    {
      text: "What is the largest state in the US?",
      options: [
        { id: 0, text: "California", isCorrect: false },
        { id: 1, text: "Alaska", isCorrect: true },
        { id: 2, text: "Texas", isCorrect: false },
        { id: 3, text: "Montana", isCorrect: false },
      ],
    },
    {
      text: "Which of the following countries DO NOT border the US?",
      options: [
        { id: 0, text: "Canada", isCorrect: false },
        { id: 1, text: "Russia", isCorrect: true },
        { id: 2, text: "Cuba", isCorrect: true },
        { id: 3, text: "Mexico", isCorrect: false },
      ],
    },
  ];

  export default questions;

Adding Questions

Now for questions, we have added a state currentQuestion with an initial 0 value and another state for a score with an initial 0 value. Then in return(), we have to modify the score value with the value of state. Then in the question card, we added a dynamic heading using <h2>Question: {currentQuestion + 1} out of {questions.length}</h2>.

After that, we have fetched the question using this questions[currentQuestion].text line of code. Now to fetch the option, we have used the map method to fetch every option, here we have fetched the text of the option using a key value. All options contain an onClick event with a function call.

In this function, we have to increase the score value if isCorrect is true, and we will add another question by increasing the value of setCurrentQuestion. For example, if the currentQuestion value is 1 then <h3 className="question-text">{questions[currentQuestion].text}</h3> this code will run and 1 question will be displayed, and if we increase the value of currentQuestion using setCurrentQuestion then we will get a 2nd question in that same div.

Basically, as soon we hit click on any option, the question will get changed to the last question.

const [currentQuestion, setCurrentQuestion] = useState(0);
  const [score, setScore] = useState(0);

const optionClicked = (isCorrect) => {
    // Increment the score
    if (isCorrect) {
      setScore(score + 1);
    }

    if (currentQuestion + 1 < questions.length) {
      setCurrentQuestion(currentQuestion + 1);
    } else {
      setShowResults(true);
    }
  };

return (
    <div className="App">
      {/* 1. Header  */}
      <h1>USA Quiz 🇺🇸</h1>

      {/* 2. Current Score  */}
      <h2>Score: {score}</h2>

      {/* 3. Show results or show the question game  */}
      {showResults ? (
        /* 4. Final Results */
        <div className="final-results">
          <h1>Final Results</h1>
          <h2>
            {score} out of {questions.length} correct - (
            20%)
          </h2>
          <button onClick={() => restartGame()}>Restart game</button>
        </div>
      ) : (
        /* 5. Question Card  */
        <div className="question-card">
          {/* Current Question  */}
          <h2>
            Question: {currentQuestion + 1} out of {questions.length}
          </h2>
          <h3 className="question-text">{questions[currentQuestion].text}</h3>

          {/* List of possible answers  */}
          <ul>
            {questions[currentQuestion].options.map((option) => {
              return (
                <li
                  key={option.id}
                  onClick={() => optionClicked(option.isCorrect)}
                >
                  {option.text}
                </li>
              );
            })}
          </ul>
        </div>
      )}
    </div>
  );
Quiz App in React

Calculating The Result

Now we are in the last stage of the quiz app, in the result part we have made some basic modifications to get the score value on the result div, and we have used (score/questions.length) * 100}% to calculate the percentage of results. Then we added a function on the restart button, in this function, we have just reset all state values back to 0 and false.

 const restartGame = () => {
    setScore(0);
    setCurrentQuestion(0);
    setShowResults(false);
  };

<div className="final-results">
          <h1>Final Results</h1>
          <h2>
            {score} out of {questions.length} correct - (
            {(score / questions.length) * 100}%)
          </h2>
          <button onClick={() => restartGame()}>Restart game</button>
        </div>
Quiz App in React

Full Source Code to Make Quiz App in React

App.js

import React, { useState } from "react";
import "./App.css";

function App() {
  // Properties
  const [showResults, setShowResults] = useState(false);
  const [currentQuestion, setCurrentQuestion] = useState(0);
  const [score, setScore] = useState(0);


  // Helper Functions

  /* A possible answer was clicked */
  const optionClicked = (isCorrect) => {
    // Increment the score
    if (isCorrect) {
      setScore(score + 1);
    }

    if (currentQuestion + 1 < questions.length) {
      setCurrentQuestion(currentQuestion + 1);
    } else {
      setShowResults(true);
    }
  };

  /* Resets the game back to default */
  const restartGame = () => {
    setScore(0);
    setCurrentQuestion(0);
    setShowResults(false);
  };

  return (
    <div className="App">
      {/* 1. Header  */}
      <h1>USA Quiz 🇺🇸</h1>

      {/* 2. Current Score  */}
      <h2>Score: {score}</h2>

      {/* 3. Show results or show the question game  */}
      {showResults ? (
        /* 4. Final Results */
        <div className="final-results">
          <h1>Final Results</h1>
          <h2>
            {score} out of {questions.length} correct - (
            {(score / questions.length) * 100}%)
          </h2>
          <button onClick={() => restartGame()}>Restart game</button>
        </div>
      ) : (
        /* 5. Question Card  */
        <div className="question-card">
          {/* Current Question  */}
          <h2>
            Question: {currentQuestion + 1} out of {questions.length}
          </h2>
          <h3 className="question-text">{questions[currentQuestion].text}</h3>

          {/* List of possible answers  */}
          <ul>
            {questions[currentQuestion].options.map((option) => {
              return (
                <li
                  key={option.id}
                  onClick={() => optionClicked(option.isCorrect)}
                >
                  {option.text}
                </li>
              );
            })}
          </ul>
        </div>
      )}
    </div>
  );
}

export default App;

Questions.js

const questions = [
    {
      text: "What is the capital of America?",
      options: [
        { id: 0, text: "New York City", isCorrect: false },
        { id: 1, text: "Boston", isCorrect: false },
        { id: 2, text: "Santa Fe", isCorrect: false },
        { id: 3, text: "Washington DC", isCorrect: true },
      ],
    },
    {
      text: "What year was the Constitution of America written?",
      options: [
        { id: 0, text: "1787", isCorrect: true },
        { id: 1, text: "1776", isCorrect: false },
        { id: 2, text: "1774", isCorrect: false },
        { id: 3, text: "1826", isCorrect: false },
      ],
    },
    {
      text: "Who was the second president of the US?",
      options: [
        { id: 0, text: "John Adams", isCorrect: true },
        { id: 1, text: "Paul Revere", isCorrect: false },
        { id: 2, text: "Thomas Jefferson", isCorrect: false },
        { id: 3, text: "Benjamin Franklin", isCorrect: false },
      ],
    },
    {
      text: "What is the largest state in the US?",
      options: [
        { id: 0, text: "California", isCorrect: false },
        { id: 1, text: "Alaska", isCorrect: true },
        { id: 2, text: "Texas", isCorrect: false },
        { id: 3, text: "Montana", isCorrect: false },
      ],
    },
    {
      text: "Which of the following countries DO NOT border the US?",
      options: [
        { id: 0, text: "Canada", isCorrect: false },
        { id: 1, text: "Russia", isCorrect: true },
        { id: 2, text: "Cuba", isCorrect: true },
        { id: 3, text: "Mexico", isCorrect: false },
      ],
    },
  ];

  export default questions;

App.css

.App {
  text-align: center;
}

.question-card {
  /* Center the div  */
  margin: 0 auto;

  /* Dimensions  */
  width: 80%; /* Can be in percentage also. */
  height: auto;

  /* Visual  */
  background-color: gray;
  padding: 16px;
  border-radius: 16px;
  color: white;
  box-shadow: rgba(50, 50, 93, 0.25) 0px 30px 60px -12px,
    rgba(0, 0, 0, 0.3) 0px 18px 36px -18px;
}

ul {
  list-style: none;
}

li {
  margin-top: 8px;
  background-color: darkgray;
  padding: 16px;
  border: 3px solid white;
  border-radius: 20px;
  font-size: 20px;
}

.question-text {
  color: darkblue;
  font-size: 24px;
}

/* Final Results  */

.final-results {
  /* Center the div  */
  margin: 0 auto;

  /* Dimensions  */
  width: 50%; /* Can be in percentage also. */
  height: auto;
  margin-top: 64px;

  /* Visual  */
  background-color: gray;
  padding: 16px;
  border-radius: 16px;
  color: white;
  box-shadow: rgba(50, 50, 93, 0.25) 0px 30px 60px -12px,
    rgba(0, 0, 0, 0.3) 0px 18px 36px -18px;
}

button {
  background-color: red; /* Green */
  border: none;
  color: white;
  padding: 16px 24px;
  text-align: center;
  text-decoration: none;
  display: inline-block;
  font-size: 16px;
  font-weight: bold;

  border-radius: 24px;
}

Output Quiz App in React

Quiz App in React

Check out the awesome video of Quiz App in React:

You may also like:

Reactjs Guru
Reactjs Guru

Welcome to React Guru, your ultimate destination for all things React.js! Whether you're a beginner taking your first steps or an experienced developer seeking advanced insights.

React tips & tutorials delivered to your inbox

Don't miss out on the latest insights, tutorials, and updates from the world of ReactJs! Our newsletter delivers valuable content directly to your inbox, keeping you informed and inspired.

3 Comments

  1. […] React Components hakkında iyi bilgi. ##React’te Sınav Uygulaması için İskelet Oluşturma Geri dönüş() ifadesinde küçük bir kodla başlayalım, sorular için, sınavın adı için bir başlık etiketi ve ardından puan için başka bir başlık ekledik. Daha sonra soru kartındaki sorumuzu ve seçeneklerini sabit bir şekilde kodladıktan sonra. Ve son olarak, doğru cevapları yeniden kodladığımız ve yeniden başlat düğmesinin bulunduğu sonuç kartını ekledik. Bu, uygulamanın yalnızca başlangıcıdır, bu nedenle şu anda sabit kodlanmıştır, ancak CSS’yi ekledikten sonra bu kodu geliştireceğiz.Devamını oku […]

  2. […] Good data of React Elements . ##Constructing Skeleton for Quiz App in React Let’s begin with somewhat exhausting code, in return() assertion, for questions, we’ve added a header tag for title of quiz, then one other heading for rating. Then, after we’ve exhausting coded our query and its choices within the query card. After which lastly we’ve added end result card the place we’ve once more exhausting coded appropriate solutions and a restart button. That is only the start of the app, so it’s proper now exhausting coded, however we are going to enhance this code after including CSS.Learn Extra […]

  3. […] Хорошее знание компонентов React. ##Создание каркаса для приложения-викторины в React Давайте начнем с небольшого жесткого кода, в операторе return() для вопросов мы добавили тег заголовка для названия викторины, а затем еще один заголовок для оценки. Затем, после того, как мы жестко закодировали наш вопрос и его варианты в карточке вопроса. И, наконец, мы добавили карточку результатов, где у нас снова жестко запрограммированы правильные ответы и кнопка перезапуска. Это только начало работы над приложением, так что сейчас оно жестко закодировано, но мы улучшим этот код после добавления CSS.Читать далее […]

Leave a Reply

Your email address will not be published. Required fields are marked *

Table of Contents