Site icon CodeARIV

Build a Quiz App in React to Test Luck

The title of this article can make you a bit confused. How can we test the luck with a quiz app? Here, we are going to make a quiz app in React to test luck with randomly generated meaningless questions and options.

We all have already attended exams with multiple-choice questions. We can not forget the below paper.

Sometimes we might guess the options and mark it. It might be correct or incorrect. It’s luck purely.

Inspiring by this art, I am going to create a quiz app to test your luck. The below representation will give an exact idea of the workflow of our app.

If you are still getting confused, take a look at the live demo.

https://testyourluck.techomoro.com/

Prerequisites

A person with a bit of knowledge in HTML, CSS, JS, and basic computer knowledge can easily understand this article.

But I recommend you to learn some basic React features from the official website.

Before entering this app, the below image will give us an exact idea of our project file structure.

1. Create a new React app

After successful installation of Node.js, we can easily create a new React project using the NPX tool with the below command.

npx create-react-app test-your-luck

Now enter the project and open it with any code editor. Here I am using Visual Studio code for editing code.

cd test-your-luck
code .

Now start our react app using npm start command.

npm start

It will open up the React application we have created in our browser window with the address https://localhost:3000. The port may vary if 3000 is busy.

If you need further assistance in the installation of React on your system, use the below links.

Install React on WindowsUbuntu, and macOS

2. Add bootstrap for faster development

We can add bootstrap to our app in different methods. Here I am using the React-bootstrap package. So Install React Bootstrap and bootstrap for the basic styling.

npm i react-bootstrap
npm i bootstrap

After installing these packages on our app, we will get a list of bootstrap components for creating UIs.

3. Install Node Sass to work with SCSS

Using Bootstrap, we can create a beautiful UI. If it requires more styling, we need to add custom CSS. But in this guide, we are using SCSS instead of CSS.

We need to install a node-sass package for adding SCSS support. So use the below command to install node-sass version 4.14.1. Right now, React does not compatible with the latest version of node-sass.

npm install node-sass@4.14.1

4. Create a component to show each Question

Now let’s start the coding. Here in this app, we are going to create a Question component to render each question. The view of a Question component is given below.

Each question will be in the format given below. It contains a name, options array, selectedOption, trueOption, and an _id.

The options array contains 4 options with name and _id.

{
   name: "Culpa tempor esse irure?"
   options: [{name: "Irure veniam irure.",_id: 1}, {name: "Tempor.",_id: 2}, {name: "Consequatincididunt."_id: 3}, {name: "Ad esse labore."_id: 4}]
   selectedOption: ""
   trueOption: 3
   _id: 9
}

Each question is rendered inside a Card and the options inside a List item.

After selecting an option, the user does not get a chance to change it. So we will disable all the options in a question after an option is selected.

disabled={question.selectedOption ? true : null} 

We are also adding a border color for the selected option. If it is the correct answer, it shows the green color and the red color border will show if it’s incorrect.

style={
 question.selectedOption === question.trueOption &&
 option._id === question.selectedOption
 ? { border: "2px solid #38bb38", borderRadius: ".3rem" }
 : question.selectedOption !== question.trueOption &&
 option._id === question.selectedOption
 ? { border: "2px solid #e24646", borderRadius: ".3rem" }
 : null
}

When clicking an option, it calls the prop checkOption. This is passed to the parent element App.js and we will discuss the logic later.

So in the final, the Question.jsx file will the same as below.

5. Create a Result modal component

After completing the quiz, it shows the results with a graph. This is Result modal component.

We are passing the number of correct answers, incorrect answers, and a function testAgain.

From this component, we will calculate the percentage of the correct answers and incorrect answers. This date is given to the PieChart.

We are using react-minimal-pie-chart package to display a pie chart.

So the complete ResultModal component will look the same as below.

6. App component

The complete logical part of our app is defined in the App component.

Here, we have initialised all the states to store questionsAndOptions, numberOfQuestions, numberOfOptions, numberOgAnsweredQustions, and numberOfCorrectAnswers

We are calling the function createQuestionAndOptions() just after mounting the App component.

useEffect(() => {
    createQuestionAndOptions();
  }, []);

The function createQuestionAndOptions() generates random questions and options. Here we are using the package lorem-ipsum to generate random paragraphs.

Lorem ipsum is a meaningless placeholder text.

    const questionLorem = new LoremIpsum({
      wordsPerSentence: {
        max: 16,
        min: 4,
      },
    });
    const optionLorem = new LoremIpsum({
      wordsPerSentence: {
        max: 3,
        min: 1,
      },
    });

We are also generating random numbers between 1 and 4 to set the correct option for each question.

So when generating each question, the trueOption value will be generated randomly.

        let questionGenerated = {
          _id: questionIndex,
          name: questionLorem.generateSentences(1).slice(0, -1) + "?",
          trueOption: randomNumber({
            min: 1,
            max: 4,
            integer: true,
          }),
          selectedOption: "",
        };

In the Question component, we are calling a prop checkOption. This will execute checkOption function in App. It adds the optionId passing from the Question component to selectedOption value of each question.

  function checkOption(questionId, optionId) {
    let updatedQuestionAndOptions = questionsAndOptions.map((question) => {
      if (question._id === questionId) {
        question.selectedOption = optionId;
        setNumberOfAnsweredQuestions(numberOfAnsweredQuestions + 1);
        if (question.selectedOption === question.trueOption) {
          setNumberOfCorrectAnswers(numberOfCorrectAnswers + 1);
        }
      }
      return question;
    });
    setQuestionsAndOptions(updatedQuestionAndOptions);
  }

So we will map through the questionAndOptions generated earlier and render the Question component in each loop.

When numberOfAnsweredQuestion = numberOfQuestions, the ResultModal component will display.

So that the complete App.js function looks the same as below.

7. Add some styles

Adding some custom styles will make our app look better. We have already installed the node-sass package. Now, inside src/assets/scss, create _navbar.scss.

Now import it to a parent element called styles.scss. We can separate the styles from styles.scss to different files and import. But I am not giving importance to it.

We will import the styles.scss in the App component.

Codesandbox

Refer to the CodeSandbox link to view the live app.

https://codesandbox.io/s/interesting-snyder-1nd0c

GitHub

You can always refer to the GitHub repository to clone this project.

https://github.com/techomoro/ReactTestYourLuck

Summary

We have learned the steps to create a quiz app in React to test luck. This will give us exact knowledge in working with a React project.

Exit mobile version