The Wayback Machine - https://web.archive.org/web/20241116084412/https://www.geeksforgeeks.org/create-a-quiz-app-using-reactjs/
Open In App

Create a Quiz App using ReactJS

Last Updated : 10 Oct, 2024
Summarize
Comments
Improve
Suggest changes
Like Article
Like
Save
Share
Report
News Follow

In this article, we will create a quiz application to learn the basics of ReactJS. We will be using class components to create the application with custom and bootstrap styling. The application will start with questions at first and then the score will be displayed at last. Initially, there are only 5 questions but you can keep adding more questions to make the quiz interesting.

Let’s have a look at what our final project will look like:

Quiz App using ReactJS

Quiz App using ReactJS

Modules required:

Steps to create the project:

Step 1: Create the project file using the command.

npx create-react-app quiz

Step 2: Navigate to the folder using the command

cd quiz

Step 3: Install the required module using the command.

npm i bootstrap

Step 4: Create a folder named components in src file and create new files Option.js, Question.js, QuestionBank.js, and Score.js

Project Structure:

 

The dependencies in package.json will look like:

package.json

"dependencies": {
"@testing-library/jest-dom": "^5.16.5",
"@testing-library/react": "^13.4.0",
"@testing-library/user-event": "^13.5.0",
"bootstrap": "^5.3.0",
"react": "^18.2.0",
"react-dom": "^18.2.0",
"react-scripts": "5.0.1",
"web-vitals": "^2.1.4"
},

Write the following codes in different files.

Example: 

  • App.js: This is our main file where all the logic for scoring and questions is written and other components are imported
  • Question.js: This component contains the question component to be displayed
  • QuestionBank.js: This component contains the raw data of the questions in our file
  • Option.js: This component has options corresponding to a particular question
  • Score.js: This component is used to display the final soce
CSS
/* App.css */

body {
  background-color: #292b2e;
  color: #ffffff;
}

.app-title {
  color: #ffffff;
  margin-top: 2rem;
}
JavaScript
// App.js

import React, { Component } from "react";
import "bootstrap/dist/css/bootstrap.min.css";
import Question from "./Components/Question";
import qBank from "./Components/QuestionBank";
import Score from "./Components/Score";
import "./App.css";

class App extends Component {
    constructor(props) {
        super(props);
        this.state = {
            questionBank: qBank,
            currentQuestion: 0,
            selectedOption: "",
            score: 0,
            quizEnd: false,
        };
    }

    handleOptionChange = (e) => {
        this.setState({ selectedOption: e.target.value });
    };

    handleFormSubmit = (e) => {
        e.preventDefault();
        this.checkAnswer();
        this.handleNextQuestion();
    };

    checkAnswer = () => {
        const { questionBank, currentQuestion, selectedOption, score } = this.state;
        if (selectedOption === questionBank[currentQuestion].answer) {
            this.setState((prevState) => ({ score: prevState.score + 1 }));
        }
    };

    handleNextQuestion = () => {
        const { questionBank, currentQuestion } = this.state;
        if (currentQuestion + 1 < questionBank.length) {
            this.setState((prevState) => ({
                currentQuestion: prevState.currentQuestion + 1,
                selectedOption: "",
            }));
        } else {
            this.setState({
                quizEnd: true,
            });
        }
    };

    render() {
        const { questionBank, currentQuestion, selectedOption, score, quizEnd } =
            this.state;
        return (
            <div className="App d-flex flex-column align-items-center justify-content-center">
                <h1 className="app-title">QUIZ APP</h1>
                {!quizEnd ? (
                    <Question
                        question={questionBank[currentQuestion]}
                        selectedOption={selectedOption}
                        onOptionChange={this.handleOptionChange}
                        onSubmit={this.handleFormSubmit}
                    />
                ) : (
                    <Score
                        score={score}
                        onNextQuestion={this.handleNextQuestion}
                        className="score"
                    />
                )}
            </div>
        );
    }
}

export default App;
JavaScript
// Question.js

import React, {Component} from "react";
import Options from "./Option";

class Question extends Component{
    render() {
        const {question, selectedOption, onOptionChange, onSubmit} = this.props;

        return(
            <div className="">
                <h3>Question {question.id}</h3>
                <h5 className="mt-2">{question.question}</h5>
                <form onSubmit={onSubmit} className="mt-2 mb-2">
                    <Options
                        options={question.options}
                        selectedOption={selectedOption}
                        onOptionChange={onOptionChange}
                    />
                    <button type="submit" className="btn btn-primary mt-2">
                        SUBMIT
                    </button>
                </form>
                
            </div>
        )
    }
}

export default Question;
JavaScript
// Option.js

import React, { Component } from 'react';

class Options extends Component {
    render() {
        const { options, selectedOption, onOptionChange } = this.props;

        return (
            <div className='options'>
                {options.map((option, index) => (
                    <div key={index} className="form-check">
                        <input
                            type="radio"
                            name="option"
                            value={option}
                            checked={selectedOption === option}
                            onChange={onOptionChange}
                            className="form-check-input"
                        />
                        <label className="form-check-label">{option}</label>
                    </div>
                ))}
            </div>
        );
    }
}

export default Options;
JavaScript
// Score.js

import React, { Component } from 'react';
import '../App.css'

class Score extends Component {
    render() {
        const { score, onNextQuestion } = this.props;

        return (
            <div>
                <h2>Results</h2>
                <h4>Your score: {score}</h4>
            </div>
        );
    }
}

export default Score;
JavaScript
// QuestionBank.js

const qBank = [
    {
        id: 1,
        question: "What is the capital of Haryana?",
        options: ["Yamunanagar", "Panipat", "Gurgaon", "Chandigarh"],
        answer: "Chandigarh",
    },
    {
        id: 2,
        question: "What is the capital of Punjab?",
        options: ["Patiala", "Ludhiana", "Amritsar", "Chandigarh"],
        answer: "Chandigarh",
    },
    {
        id: 3,
        question: "What is the capital of India?",
        options: ["Delhi", "Mumbai", "Kolkata", "Chennai"],
        answer: "Delhi"
    },
    {
        id: 4,
        question: "What is the capital of Uttarakhad?",
        options: ["Roorkee", "Haridwar", "Dehradun", "Nanital"],
        answer: "Dehradun"
    },
    {
        id: 5,
        question: "What is capital of Uttar Pradesh?",
        options: ["GB Nagar", "Lucknow", "Prayagraj", "Agra"],
        answer: "Lucknow"
    },
]

export default qBank;


Building a quiz app is a fun way to apply your React knowledge. The ReactJS Course features a project-based approach to creating interactive applications like quiz apps, helping you practice your coding skills effectively.

Steps to run the application:

Step 1: Type the following command in your command line

npm start

Step 2: Open http://localhost:3000/ URL in the browser. It will display the result.

Output:

Peek-2023-06-07-12-36

Previous Article
Next Article

Similar Reads

Create a New React App - npm create-react-app
The create react app command allows us to create a development environment and install all necessary libraries for creating single-page applications using React. The CRA tool is used to set up a new React project quickly, providing a standard structure and configuration. It includes a development server, build scripts, and support for modern JavaSc
3 min read
How to create a Color-Box App using ReactJS?
Basically we want to build an app that shows the number of boxes which has different colors assigned to each of them. Each time the app loads different random colors are assigned. when a user clicks any of the boxes, it changes its color to some different random color that does not equal to its previous color value. We create three components 'App'
5 min read
Create a QR code generator app using ReactJS
In this article, we will create a simple QR Code generator app. A QR code is a two-dimensional barcode that can be read by smartphones. It allows the encoding of more than 4,000 characters in a compact format. QR codes can be used for various purposes, such as displaying text to users, opening URLs, storing contact information in an address book, o
3 min read
How to create a food recipe app using ReactJS ?
We are going to make a food recipe app using React.js. Pre-requisite:React hooksReact componentsJavaScript ES6API CSSApproach: Here in this app we should have a component where we are going to show our food recipes. And we need to fetch all the required food recipes using a food recipe API. We will fetch the API data, store those data in a componen
4 min read
Create a Coin Flipping App using ReactJS
In this article, we will build a coin flipping application. In which the user can flip a coin and get a random result from head or tails. We create three components 'App' and 'FlipCoin' and 'Coin'. The app component renders a single FlipCoin component only. FlipCoin component contains all the behind the logic. It has a default prop coin that is an
3 min read
How to create a Location finder app using ReactJS ?
In this article, we will be building a location finder app that lets you search for different places on a map. Our app contains two sections, one for displaying the marker on the map and the other is for searching different places. For rendering the map and getting the coordinates for the searched location, we will be using Mapbox. Through this art
4 min read
Create ToDo App using ReactJS
In this article, we will create a to-do app to understand the basics of ReactJS. We will be working with class based components in this application and use the React-Bootstrap module to style the components. This to-do list can add new tasks we can also delete the tasks by clicking on them. The logic is handled by a click event handler whenever the
4 min read
How to create an Avatar generator app in ReactJS ?
In this article, we are going to make a simple avatar generator app that generates random images. In this avatar generator, we have several buttons for different categories to choose from, the next button to generate random images, and a download button to finally download your favorite avatar. Prerequisites: The pre-requisites for this project are
3 min read
How to create a Dictionary App in ReactJS ?
In this article, we will be building a very simple Dictionary app with the help of an API. This is a perfect project for beginners as it will teach you how to fetch information from an API and display it and some basics of how React actually works. Also, we will learn about how to use React icons. Let's begin. Approach: Our app contains two section
4 min read
Create an Interactive Quiz App using React-Native?
In this article, we are going to implement an Interactive Quiz App using React Native. Interactive Quiz App is a mobile application that allows users to take tests and view their quiz results to see how well they performed. This Interactive Quiz App consists of multiple questions and multiple-choice answers to each question. Preview of final output
4 min read
Create a Quiz App with Timer using HTML CSS and JavaScript
In this tutorial, we'll guide you through the process of building an engaging Quiz App with a built-in timer, utilizing HTML, CSS, and JavaScript. This application is designed to present users with a curated set of questions, each accompanied by a countdown timer, providing an interactive and time-bound quiz experience. Additionally, the app keeps
7 min read
Create a Quiz App using React Hooks and Timer-Based State Management
Quiz Application is a web-based application built using React Hooks and Timer-Based State Management. It provides users with a series of multiple-choice questions and requires them to select an option within a given time limit. If the user fails to select an option within the specified time, the application automatically moves to the next question.
5 min read
Create a Quiz App with Next JS
In this article, we’ll explore the process of building a Quiz App utilizing NextJS. The quiz app provides users with a series of multiple-choice questions with options. Users can select the option and move to the next question. At the end, the user will be able to see the analysis of the quiz. Output Preview: Let us have a look at how the final out
5 min read
Create a Quiz App with Next JS and Tailwind
We’ll explore the process of building a Quiz App utilizing NextJS and Tailwind. The quiz app provides users with a series of multiple-choice questions with options. Users can select the option and move to the next question. At the end, the user will be able to see the analysis of the quiz. PrerequisitesNPM & NodeJSReactReact JS HooksNext JSTail
6 min read
Deploying Your Web App using Azure App Service
Pre-requisite: Introduction to Microsoft Azure | A cloud computing service The majority of Computer Science students start with Web Development or Machine Learning. Now after learning how to create a website, we should learn to deploy it online. By deploying our website, we can share it with others, perform alpha or beta testing, perform live chang
4 min read
IP address finder app using ReactJS
In this article, we will be building an IP address finder app that lets you find your client's approximate location on a map. An IP address is a unique address that identifies a device on the internet or a local network. IP stands for "Internet Protocol," which is the set of rules governing the format of data sent via the internet or local network.
4 min read
Build a Anagram Checker App Using ReactJS
In this article, we will create an Anagram Checker App using React. Anagrams are­ words or phrases that can be formed by re­arranging the letters of anothe­r word or phrase, using each lette­r exactly once. This app will enable users to enter two words or phrase­s and determine if they are anagrams of each other. Moreover, it provides the option fo
4 min read
How to develop a Progressive Web App using ReactJS ?
Progressive React Applications respond very fast to user actions. They load fast and are engaging just like a mobile app. They can access Mobile device features, leverage the Operating System, and have a very high reach. It enables Installability, Background Syncing, Caching and Offline Support, and other features like Push Notifications. With Reac
10 min read
Build a Random User Generator App Using ReactJS
In this article, we will create a random user generator application using API and React JS. A Random User Generator App Using React Js is a web application built with the React.js library that generates random user profiles. It typically retrieves and displays details like names, photos, and contact information to simulate user data for testing and
4 min read
Random Quote Generator App using ReactJS
In this article, we will create an application that uses an API to generate random quotes. The user will be given a button which on click will fetch a random quote from the API and display it on the screen. Users can generate many advices by clicking the button again. The button and the quotes are displayed beautifully using CSS styling to create a
3 min read
Blog app using ReactJS
In this article, we have created the blog app using react js, First of all, we have created the project name blog by entering the command npx create-react-app blog and installing all modules. Then we create the folder name component under src and make two jsx file post.jsx and posts.jsx and styling the jsx component by post.css and posts.css. And l
5 min read
How to log-out user from app using ReactJS ?
The objective of this article is to how we can set up, log out a user, and retrieve data from local memory User Browser storage in the React app. During the sign-in session, we will save the user details to the browser's local storage, and also during the time of logout, we will remove the user's details from the local storage.  PrerequisitesReact
3 min read
User to User private Chat App using ReactJS and Firebase | Without socket programming
This article covers how to make a User to User private Chat App using React JS and Firebase (without socket programming). React is a JavaScript framework provided by Facebook and is used to build fully-featured web applications. We will be following the below steps for creating our application: npx create-react-app chat-appcd chat-appNow install al
10 min read
Paint App using ReactJS
In this article, we will be building a simple paint application that lets you draw just like in MS-Paint. Through this article, we will learn how to implement and work with canvas in React.js. Our app contains two sections, one for drawing and the other is a menu where the user can customize the brush color, width, and opacity. The user will be pro
4 min read
Movie Trailer app using ReactJS
In this article, we are going to make a simple app that searches for any movie/web series trailers. The users can search for their favourite movie trailers using this application. The API will fetch the trailer from the internet and display it on the webpage. We will use 'movie-trailer' npm package to find such URLs and display the content using an
3 min read
Build a simple Song Lyrics Finder app using ReactJS
React is a super-awesome front-end library that we can use to build user interfaces. In this article, we will be building a simple application to find the lyrics of any song. This is a perfect project for beginners as it will teach you how to fetch information using an API and display that information accordingly. Prerequisites: The pre-requisites
3 min read
Cryptocurrency App using ReactJS
In this article, we are going to build a cryptocurrency app that lists all the available cryptos in the market. In this application user can see the current price, market cap, available supply of all the cryptocurrencies. The user can also search for an individual crypto coin and get information about it. We will convert the currency into INR by pa
3 min read
Currency converter app using ReactJS
In this article, we will be building a very simple currency converter app with the help of an API. Our app contains three sections, one for taking the user input and storing it inside a state variable, a menu where users can change the units of conversion, and finally, a display section where we display the final results. Let us have a look at how
4 min read
Dice Rolling App using ReactJS
This article will create a dice-rolling application that rolls two dice and displays a random number between 1 and 6 as we click the button both dice shake and generate a new number that shows on the upper face of the dice (in dotted form as a standard dice). The numbers on the upper face are generated randomly each time we roll the dice. There are
5 min read
Introduction to Xamarin | A Software for Mobile App Development and App Creation
The entire world is now surrounded by billions and trillions of mobile Tech which is inevitable. The major share of the development of mobile apps is taken by the Google's Android, Apple's iOS, and Microsoft's Windows. Every new learner or newbie in Mobile Development Domain finds himself in the dilemma of choosing the platform to start with. They
9 min read
three90RightbarBannerImg