Make a simple Quiz app using React.

Make a simple Quiz app using React

This is how our Quiz app is going to appear and work πŸ‘‡

Make a simple Quiz app using React tutorial Video

The first step would be setting up our React application and for that, you need to choose a development environment. For this project, we’ll use create-react-app, but feel free to choose another environment that suits your preferences.

To setup your react application follow these steps :

1. Run the following command in your terminal:

npx create-react-app my-quiz

if the above command doesn’t work, run this command:

npm init react-app my-quiz

2. Navigate to the root directory of your new React app:

cd my-quiz

3. Run your build process with `npm start`:

npm start

We have setup our react application, Now we will create theΒ UIΒ of our Quiz app.

Creating UI :-

Note: If you would like to save time and avoid the task of creating a user interface, you can easily access the UI code from my GitHub repository. Simply
Click here. The main code for the app can be found in the App.js file, and the styling code is in index.css.

To create the user interface (UI), we will begin by adding a <div> element with the “className” attribute set to “app” then we will use a ternary operator ({false ? ... : ...}) to conditionally render different elements based on whether the user has answered all the questions. In this case, the condition is hardcoded as “false” for demonstration purposes. If the condition is “false“, it renders the question section and answer section. Otherwise, it renders a score section that displays the user’s score.

Now we will create two section inside the div “app”, first one is “question-section” and the second is “answer-section”. The question section is wrapped inside a div with the class name “question-section”. It contains two child elements:

  • A `div` with the class name “question-count” that displays the current question number and the total number of questions.
  • A `div` with the class name “question-text” that should display the text of the current question. However, the placeholder text “This is where the question text should go” is currently displayed.

The answer section is wrapped inside a div with the class name “answer-section”. It contains four answer options, each represented by a button element. The button text represents the answer option.

Then we will create an array called questions“. This array holds four question objects, each containing a “questionText” and an array of “answerOptions“.

Each “answerOptions” array will contain four objects with an “answerText” and an “isCorrect” property, representing the possible answer options for the corresponding question. The “isCorrect” property is a boolean indicating whether the answer option is correct or not.

App.js : πŸ‘‡


function App() {
  const questions = [
    {
      questionText: "What is the capital of France?",
      answerOptions: [
        { answerText: "New York", isCorrect: false },
        { answerText: "London", isCorrect: false },
        { answerText: "Paris", isCorrect: true },
        { answerText: "Dublin", isCorrect: false },
      ],
    },
    {
      questionText: "Who is CEO of Tesla?",
      answerOptions: [
        { answerText: "Jeff Bezos", isCorrect: false },
        { answerText: "Elon Musk", isCorrect: true },
        { answerText: "Bill Gates", isCorrect: false },
        { answerText: "Tony Stark", isCorrect: false },
      ],
    },
    {
      questionText: "The iPhone was created by which company?",
      answerOptions: [
        { answerText: "Apple", isCorrect: true },
        { answerText: "Intel", isCorrect: false },
        { answerText: "Amazon", isCorrect: false },
        { answerText: "Microsoft", isCorrect: false },
      ],
    },
    {
      questionText: "How many Harry Potter books are there?",
      answerOptions: [
        { answerText: "1", isCorrect: false },
        { answerText: "4", isCorrect: false },
        { answerText: "6", isCorrect: false },
        { answerText: "7", isCorrect: true },
      ],
    },
  ];

  return (
    <div className="app">
      {/* HINT: replace "false" with logic to display the 
      score when the user has answered all the questions */}
      {false ? (
        <div className="score-section">
          You scored 1 out of {questions.length}
        </div>
      ) : (
        <>
          <div className="question-section">
            <div className="question-count">
              <span>Question 1</span>/{questions.length}
            </div>
            <div className="question-text">
              This is where the question text should go
            </div>
          </div>
          <div className="answer-section">
            <button>Answer 1</button>
            <button>Answer 2</button>
            <button>Answer 3</button>
            <button>Answer 4</button>
          </div>
        </>
      )}
    </div>
  );
}

export default App;

index.css : πŸ‘‡

body {
  margin: 0;
  font-family: -apple-system, BlinkMacSystemFont, "Segoe UI", "Roboto", "Oxygen",
    "Ubuntu", "Cantarell", "Fira Sans", "Droid Sans", "Helvetica Neue",
    sans-serif;
  -webkit-font-smoothing: antialiased;
  -moz-osx-font-smoothing: grayscale;
}
* {
  font-family: "Verdana", cursive, sans-serif;
  color: #ffffff;
}

body {
  background-color: #7cc6fe;
  display: flex;
  justify-content: center;
  align-items: center;
  min-height: 100vh;
}

.app {
  background-color: #252d4a;
  width: 450px;
  min-height: 200px;
  height: min-content;
  border-radius: 15px;
  padding: 20px;
  box-shadow: 10px 10px 42px 0px rgba(0, 0, 0, 0.75);
  display: flex;
  justify-content: space-evenly;
}

.score-section {
  display: flex;
  font-size: 24px;
  align-items: center;
}

/* QUESTION/TIMER/LEFT SECTION */
.question-section {
  width: 100%;
  position: relative;
}

.question-count {
  margin-bottom: 20px;
}

.question-count span {
  font-size: 28px;
}

.question-text {
  margin-bottom: 12px;
}

.timer-text {
  background: rgb(230, 153, 12);
  padding: 15px;
  margin-top: 20px;
  margin-right: 20px;
  border: 5px solid rgb(255, 189, 67);
  border-radius: 15px;
  text-align: center;
}

/* ANSWERS/RIGHT SECTION */
.answer-section {
  width: 100%;
  display: flex;
  flex-direction: column;
  justify-content: space-between;
}

button {
  width: 100%;
  font-size: 16px;
  color: #ffffff;
  background-color: #252d4a;
  border-radius: 15px;
  display: flex;
  padding: 5px;
  justify-content: flex-start;
  align-items: center;
  border: 5px solid #234668;
  cursor: pointer;
}

.correct {
  background-color: #2f922f;
}

.incorrect {
  background-color: #ff3333;
}

button:hover {
  background-color: #555e7d;
}

button:focus {
  outline: none;
}

button svg {
  margin-right: 5px;
}

Now your Quiz app should look like this πŸ‘‡:

Make a simple Quiz app using React UI image

Showing Question and Answer on the screen :-

To show the question and answer on the screen we will destructure the array “questions”.

App.js : πŸ‘‡

// function App() {
  const questions = [
    {
      questionText: "What is the capital of France?",
      answerOptions: [
        { answerText: "New York", isCorrect: false },
        { answerText: "London", isCorrect: false },
        { answerText: "Paris", isCorrect: true },
        { answerText: "Dublin", isCorrect: false },
      ],
    },
    {
      questionText: "Who is CEO of Tesla?",
      answerOptions: [
        { answerText: "Jeff Bezos", isCorrect: false },
        { answerText: "Elon Musk", isCorrect: true },
        { answerText: "Bill Gates", isCorrect: false },
        { answerText: "Tony Stark", isCorrect: false },
      ],
    },
    {
      questionText: "The iPhone was created by which company?",
      answerOptions: [
        { answerText: "Apple", isCorrect: true },
        { answerText: "Intel", isCorrect: false },
        { answerText: "Amazon", isCorrect: false },
        { answerText: "Microsoft", isCorrect: false },
      ],
    },
    {
      questionText: "How many Harry Potter books are there?",
      answerOptions: [
        { answerText: "1", isCorrect: false },
        { answerText: "4", isCorrect: false },
        { answerText: "6", isCorrect: false },
        { answerText: "7", isCorrect: true },
      ],
    },
  ];

//  return (
//    <div className="app">
//      {false ? (
//        <div className="score-section">
//          You scored 1 out of {questions.length}
//        </div>
//      ) : (
//        <>
//          <div className="question-section">
//            <div className="question-count">
//              <span>Question 1</span>/{questions.length}
//            </div>
            <div className="question-text">{questions[0].questionText}</div>
//          </div>
//          <div className="answer-section">
            {questions[0].answerOptions.map((item) => (
              <button>{item.answerText}</button>
            ))}
//          </div>
//        </>
//      )}
//    </div>
//  );
// }

// export default App;

This is how our Quiz app will look after the above code : πŸ‘‡

Make a simple Quiz app using React working image

Checking Answers and changing Questions :-

Now we will create three state variables “currentQuestion”, “showScore” and “score” with the initial value of 0, false and 0 respectively.

The variable “currentQuestion” will keep track of the number of questions being asked. The variable “showScore” will have a true or false value indicating whether the user has answered all the questions or not. The variable “score” will store the number of correctly answered questions at the end.

Next, we will create a function called “handleAnswerClicked.” This function will contain the logic for checking the correctness of the answer, updating the value of “currentQuestion” every time an answer button is clicked, and performing other necessary operations.

After creating the “handleAnswerClicked” function, we will assign it to the onClick event of the button component. This means that when the button is clicked, the code inside the “handleAnswerClicked” function will be executed. We will also add any additional code that is necessary for the functioning of the button.

App.js : πŸ‘‡

import { useState } from "react";

function App() {
  const questions = [
    {
      questionText: "What is the capital of France?",
      answerOptions: [
        { answerText: "New York", isCorrect: false },
        { answerText: "London", isCorrect: false },
        { answerText: "Paris", isCorrect: true },
        { answerText: "Dublin", isCorrect: false },
      ],
    },
    {
      questionText: "Who is CEO of Tesla?",
      answerOptions: [
        { answerText: "Jeff Bezos", isCorrect: false },
        { answerText: "Elon Musk", isCorrect: true },
        { answerText: "Bill Gates", isCorrect: false },
        { answerText: "Tony Stark", isCorrect: false },
      ],
    },
    {
      questionText: "The iPhone was created by which company?",
      answerOptions: [
        { answerText: "Apple", isCorrect: true },
        { answerText: "Intel", isCorrect: false },
        { answerText: "Amazon", isCorrect: false },
        { answerText: "Microsoft", isCorrect: false },
      ],
    },
    {
      questionText: "How many Harry Potter books are there?",
      answerOptions: [
        { answerText: "1", isCorrect: false },
        { answerText: "4", isCorrect: false },
        { answerText: "6", isCorrect: false },
        { answerText: "7", isCorrect: true },
      ],
    },
  ];

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

  const handleAnswerOptionClick = (isCorrect) => {
    if (isCorrect) {
      setScore(score + 1);
    }

    const nextQuestion = currentQuestion + 1;
    if (nextQuestion < questions.length) {
      setCurrentQuestion(nextQuestion);
    } else {
      setShowScore(true);
    }
  };

  return (
    <div className="app">
      {showScore ? (
        <div className="score-section">
          You scored {score} out of {questions.length}
        </div>
      ) : (
        <>
          <div className="question-section">
            <div className="question-count">
              <span>Question {currentQuestion + 1}</span>/{questions.length}
            </div>
            <div className="question-text">
              {questions[currentQuestion].questionText}
            </div>
          </div>
          <div className="answer-section">
            {questions[currentQuestion].answerOptions.map((answerOption) => (
              <button
                onClick={() => handleAnswerOptionClick(answerOption.isCorrect)}
              >
                {answerOption.answerText}
              </button>
            ))}
          </div>
        </>
      )}
    </div>
  );
}

export default App;

Adding Play Again button :-

To add the play again functionality we will first create a play again button inside the “score-section” div.

App.js : πŸ‘‡

<div className="score-section">
          You scored {score} out of {questions.length}
          <button>Play Again</button>
        </div>

Next, we will add the functionality of play again in the onClick() event of the button.

App.js : πŸ‘‡

// <div className="score-section">
//          You scored {score} out of {questions.length}
//          <button
            onClick={() => {
              setShowScore(false);
              setCurrentQuestion(0);
              setScore(0);
            }}
//          >
//            Play Again
//          </button>
//        </div>

Here we have completed our Quiz app, hope you liked the tutorial. πŸ™

ALSO SEE – HOW TO MAKE A BASIC FORM USING REACT AND FORMIK.
ALSO SEE – HOW TO MAKE A SEARCH FILTER USING REACT.
ALSO SEE – HOW TO MAKE A TEMPERATURE CONTROLLER USING REACT.


Leave a Reply

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