How to Create a Quiz App in React: Step-by-Step Guide with Source Code

  • react-js
  • 82 Views
  • 4 Min Read
  • 9 May 2024

Hi Developer! Today in this article, I will give you the best technique for creating a quiz app by using React without installing other libraries.

 

Quiz App UI Design

 

In this article, we have walked you through each step of building a quiz application using React with code examples, providing both educational value and practical experience. We are confident that, by the end of this article, you will be able to create a great quiz app.

 

So let's get started.

 

Prerequisites to Make a Quiz App in React

 

  • Familiarity with ReactJS: 
  • Knowledge of React Hooks: 
  • Knowledge of React Props:
  • Knowledge of React Components:

 

 

How can we build logic for this quiz app?

 

When you're making a quiz app, you need to think about how it's going to work. Like, how are we going to show the questions? And how will people answer them? Also, we need to know whether the answer given by the user is right or wrong. So, we need to plan it out well to make sure it runs nice and smoothly. Let's break it down into simple steps, so our Quiz App is super easy for everyone to use.

 

 

Create a quiz app step-by-step

 

Step 1: Set Up Your React Project

 

First, let's set up a new React project using the Create React App. Open your terminal and run the following commands:

   
npx create-react-app quiz-app

cd quiz-app
   

This will create a new React project named quiz-app and navigate you into its directory.

 

Step 2: Structure Your Project

 

First, create two new files named Quiz.jsx and Question.jsx within your components folder located in the src directory. Next, create a question.json file within your data folder, also located in the src directory.

 

Quiz App Folder Structure

 

Step 3: Create Quiz Data

 

Define the quiz questions by utilizing a questions.json file located within the data folder.

 
[
    {
        "question": "What is React?",
        "options": [
            "A database management system",
            "A programming language",
            "A JavaScript library for building user interfaces ",
            "A web browser"
        ],
        "answer": "A JavaScript library for building user interfaces "
    },
    {
        "question": "What is the purpose of a constructor in JavaScript?",
        "options": [
            "To style HTML elements",
            "To initialize an object's properties",
            "To create a new database table",
            "To fetch data from an API"
        ],
        "answer": "To initialize an object's properties"
    },
    {
        "question": "What does DOM stand for in JavaScript?",
        "options": [
            "Document Object Model",
            "Database Object Model",
            "Document Oriented Model",
            "Data Object Model"
        ],
        "answer": "Document Object Model"
    }
]

 

This JSON data holds a series of quiz questions stored in a format that's easy to work with. Each question comes with its own details:

 

  • "question": It holds the question that users will see and try to answer.
  • "options": This array lists the different choices users can pick from as their answer.
  • "answer": This specifies which option is the correct answer to the question.
 
When we organize quiz questions like this, it's easier to handle and show them to people using quiz apps.

 

Step 4: Get question data and build logic

 

Include the following code in the Question.jsx file:

 
// Question.jsx
import React from 'react';

const Question = ({ question, options, onSelect }) => {
    return (
        <div>
            <h3>{question}</h3>
            <div className="options">
                {options.map(option => (
                    <button key={option} onClick={() => onSelect(option)}>{option}</button>
                ))}
            </div>
        </div>
    );
};

export default Question;

 

This code represents a component in React named "Question". It's like a building block used to create a quiz app. Here's what it does:

 

  • It takes three things: the question itself ("question"), the possible answers ("options"), and a way to handle when a user selects an answer ("onSelect").

 

  • When you use this component, it shows the question and a bunch of buttons, each with one of the possible answers.

 

  • When a user clicks on a button, the "onSelect" function is triggered. It helps the app know which answer the user picked.

 

Quiz.jsx file:

 

// Quiz.jsx
import React, { useEffect, useState } from 'react';
import Question from './Question';
import questionsData from '../data/question.json';

const Quiz = () => {
    // State variables to manage quiz progress and completion
    const [currentQuestion, setCurrentQuestion] = useState(0);
    const [score, setScore] = useState(0);
    const [quizCompleted, setQuizCompleted] = useState(false);
    const [completionMessage, setCompletionMessage] = useState('');

    // Function to handle user's answer selection
    const handleAnswerSelect = (selectedOption) => {
        const currentAnswer = questionsData[currentQuestion].answer;
        if (selectedOption === currentAnswer) {
            setScore(score + 1);
        }
        const nextQuestion = currentQuestion + 1;
        if (nextQuestion < questionsData.length) {
            setCurrentQuestion(nextQuestion);
        } else {
            setQuizCompleted(true);
        }
    };

    // Effect to determine completion message whenever score changes
    useEffect(() => {
        determineCompletionMessage(score);
    }, [score]);

    // Function to determine completion message based on score
    const determineCompletionMessage = (currentScore) => {
        const totalQuestions = questionsData.length;
        if (currentScore === 0) {
            setCompletionMessage(`Oops, you scored ${currentScore}/${totalQuestions}. You are wrong.`);
        } else if (currentScore === totalQuestions) {
            setCompletionMessage(`🎉Congratulations! You scored ${currentScore}/${totalQuestions}. You did well.`);
        } else {
            setCompletionMessage(`Good, but you scored ${currentScore}/${totalQuestions}. Do some more practice.`);
        }
    };

    // Function to restart the quiz
    const handleRestartQuiz = () => {
        setCurrentQuestion(0);
        setScore(0);
        setQuizCompleted(false);
        setCompletionMessage('');
    };

    // JSX to render quiz components based on quiz state
    return (
        <div className="quiz-container">
            <h1>Quiz App</h1>
            {!quizCompleted ? (
                <>
                    <Question
                        question={questionsData[currentQuestion].question}
                        options={questionsData[currentQuestion].options}
                        onSelect={handleAnswerSelect}
                    />
                    <div className="score">Score: {score}/{questionsData.length}</div>
                </>
            ) : (
                <div className="quiz-completed fade-in">
                    <h2>Quiz Completed!</h2>
                    <p>{completionMessage}</p>
                    <button onClick={handleRestartQuiz}>Restart Quiz</button>
                </div>
            )}
        </div>
    );
};

export default Quiz;
 

The 'Quiz' React component is important for making a quiz app. Let's dive into its features!

 

  • State Management: The component efficiently tracks the quiz's progress, including the current question, the user's score, and completion status.

 

  • Answer Selection: Through the "handleAnswerSelect" function, users can select answers. If correct, the score updates accordingly, and the quiz progresses to the next question.

 

  • useEffect: In this case, useEffect makes sure the completion message always shows the right score. So, whenever the user's score changes, the message updates too. That way, users get the latest and most accurate feedback.

 

  • Completion Message: A dynamic completion message is generated based on the user's score. After finishing the quiz, it lets users know how they did, so they understand their performance! It's like feedback.

 

  • Restart Capability: Users have the option to restart the quiz once completed, allowing for additional attempts. This functionality resets all progress, providing a fresh start.

 

  • Rendering Logic: The component dynamically renders quiz questions and options based on the current state. When the quiz is completed, a message displays along with an option to restart, ensuring a seamless user experience.

 

Step 5: Integrate the quiz Component

 

Open App.js and replace its content with the following:

 

// App.js
import React from 'react';
import './App.css';
import Quiz from './components/Quiz'

function App() {
    return (
        <div className="App">
            <Quiz />
        </div>
    );
}

export default App;

 

This code initializes a React application by rendering the "Quiz" component within a div with the class "App", styling applied from an external CSS file.

 

You can add this code in the App.css file for UI design.

 

body {
  font-family: sans-serif;
  background-color: steelblue;
  color: white;
}

.quiz-container {
  border: 5px solid rgb(106, 162, 207);
  border-radius: 5px;
  max-width: 600px;
  margin: 200px auto;
  padding: 20px 50px;
}

.options {
  display: grid;
  grid-template-columns: repeat(2, 1fr);
  grid-gap: 10px;
}

button {
  padding: 10px;
  border-radius: 5px;
  background-color: rgb(37, 37, 37);
  color: white;
  border: none;
  cursor: pointer;
}

button:hover {
  background-color: black
}

.score {
  margin-top: 20px;
  font-size: 18px;
}

.quiz-completed {
  text-align: center;
}

.quiz-completed button {
  margin-top: 20px;
}

.quiz-completed {
  text-align: center;
  opacity: 0;
}

.fade-in {
  animation: fadeInAnimation 1s ease-in forwards;
}

@keyframes fadeInAnimation {
  from {
    opacity: 0;
  }

  to {
    opacity: 1;
  }
}

 

 

Step 6: Run Your Application 

 

Now, let's test our quiz app. Go to the project folder (quiz-app) in the terminal and type the command to run it.

 
npm start

 

React Quiz App project output

 

Good! We have built a quiz app using React that works well. You can make it even better. So go ahead and make it even better and increase your skills.

 

 

Conclusion

 

Building the quiz app while learning React improves our React development experience. By following all of the steps listed in this guide, you will have created an excellent quiz app. To further increase user engagement, you can add more functionality to this project, such as timer functionality, difficulty levels, or a multiplayer option, which will also boost your skills.

 

If you have any questions regarding this article or any other web development, then you can ask them in the question box given below, and you will get an answer soon.

Didn't find your answer? Add your question.

Share

Comments (0)

No comments yet. Be the first to comment!

About Author

Username

Diya Jain ( diya )

The Dev without a Degree

Joined On 10 Apr 2024

More from Diya Jain

10 Fun Websites for Stress Relief and Relaxation During Coding Breaks

programming

11 Nov 2024

Top 10 fun websites for coders to relax during breaks. Recharge with interactive games, ar....

How to Implement Undo Functionality for Deleting Items in Your React App

react-js

28 Sep 2024

Learn how to implement undo functionality for deleting items in React. Follow a step-by-st....

Top Strategies for Search Bar Optimization on Major Platforms

web-development

6 Sep 2024

Discover top strategies for search bar optimization on major platforms. Enhance real-time ....

Top Strategies to Optimize ReactJS Application Performance for Faster Load Times

react-js

23 Aug 2024

From this article, you will discover the best practices to enhance the speed of loading yo....

Comprehensive Guide to Tooltips in ReactJS

react-js

5 Jun 2024

Explore ReactJS tooltips from start to finish! Learn how to add, customize, troubleshoot, ....

Comprehensive Guide to React Hooks: When and How to Use Each Hook Effectively

react-js

9 Jul 2024

In React, we use a component-based structure. A component is like a building block of code....

Popular Posts from Code Mafias

10 Fun Websites for Stress Relief and Relaxation During Coding Breaks

programming

11 Nov 2024

Top 10 fun websites for coders to relax during breaks. Recharge with interactive games, ar....

Mastering HTML: Top 12 Unique HTML Tags with Examples

html

4 May 2024

Through this article, learn those essential HTML tags that many developers do not know abo....

Top 60 Eye-Catching Button Designs Users Can’t Wait to Click - With Source Code

ui-ux

11 Oct 2024

Discover 60 eye-catching button designs with source code, crafted with HTML and CSS to enh....

How to Upload Code to GitHub: Quick Steps and Detailed Instructions for Beginners

github

16 Sep 2024

In order to upload (push) your project to GitHub, it involves multiple steps that need to ....

How to install MongoDB on windows in 2024

mongodb

2 May 2024

MongoDB is a Database Management System based on NoSQL (Not Only SQL) and utilizes JSON-li....

How to Implement Undo Functionality for Deleting Items in Your React App

react-js

28 Sep 2024

Learn how to implement undo functionality for deleting items in React. Follow a step-by-st....