Open In App

How to build a Quiz App with React and TypeScript ?

Last Updated : 23 Nov, 2023
Improve
Improve
Like Article
Like
Save
Share
Report

TypeScript is an open-source programming language, developed and maintained by Microsoft. It is a strongly typed language that builds on JavaScript. It is usually used in large-scale projects. It follows JavaScript syntax and adds more features to it.

ReactJS is an open-source Javascript library specially used to design UI(user interfaces) mainly single-page applications. Having a large developer community it is widely used for making single-page applications.

Prerequisites:

Approach:

A simple Quiz App that contains a set of curated questions and their answers and checks for the correctness of the answer given by the user. It navigates through the questions using dynamic programming. A quiz can be used as a method of assessment in education and other similar fields to measure knowledge or skills.

Steps to Create the React Application And Installing Module:

Step 1: Run the following commands to create a new React project using the create-react-app package:

npx create-react-app quiz-app --template typescript

Step 2: Change the directory to the project root directory:

cd quiz-app

Step 3: Change directory to src:

cd src

Step 4: Delete everything inside the directory

rm *

Step 5: Now will create a components directory in the src folder and Question.tsx and Quiz.tsx files in it.

mkdir components && cd components && touch Question.tsx
touch Quiz.tsx

Step 6: Now we will go to the src directory using these commands:

cd ..

Step 7: The src directory will create an index.tsx, App.tsx, and index.css using the following commands:

touch index.tsx && touch index.css && touch App.tsx

Project Structure:

Project Structure

The updated dependencies in package.json file will look like:

"dependencies": {
"react": "^18.2.0",
"react-dom": "^18.2.0",
"react-scripts": "5.0.1",
"web-vitals": "^2.1.4",
}

Example 1: Below is the implementation of the Quiz App.

Javascript




//index.tsx
import React from 'react';
import ReactDOM from 'react-dom/client';
import './index.css';
import App from './App';
 
const root = ReactDOM.createRoot(
    document.getElementById('root') as HTMLElement
);
root.render(
    <React.StrictMode>
        <App />
    </React.StrictMode>
);


Javascript




//Question.tsx
import React from 'react';
 
interface Props {
    question: string;
    choices: string[];
    answer: string;
    onAnswer: (answer: string) => void;
}
 
const Question: React.FC<Props> = (
    { question, choices, answer, onAnswer }) => {
    return (
        <div className="d-flex
                        justify-content-center
                        align-center
                        text-center
                        flex-column">
            <h2 className="">{question}</h2>
            <div className="">
                {choices.map((choice) => (
                    <button className="btn btn-success m-2"
                        onClick={() => onAnswer(choice)}>
                                        {choice}</button>
                ))}
            </div>
        </div>
    );
};
 
export default Question;


Javascript




//Quiz.tsx
import React, { useState } from 'react';
import Question from './Question';
 
const questions = [
    {
        question: 'What is the capital of France?',
        choices: ['Paris', 'London', 'New York'],
        answer: 'Paris',
    },
    {
        question: 'What is the largest planet in our solar system?',
        choices: ['Mars', 'Jupiter', 'Venus'],
        answer: 'Jupiter',
    },
    {
        question: 'What is the boiling point of water?',
        choices: ['100°C', '0°C', '50°C'],
        answer: '100°C',
    },
    {
        question: 'What is the largest planet in our solar system?',
        choices: ['Mars', 'Jupiter', 'Venus'],
        answer: 'Jupiter',
    },
    {
        question: 'What is the boiling point of water?',
        choices: ['100°C', '0°C', '50°C'],
        answer: '100°C',
    },
];
 
const Quiz: React.FC = () => {
    const [currentQuestion, setCurrentQuestion] = useState(0);
    const [score, setScore] = useState(0);
 
    const handleAnswer = (answer: string) => {
        if (answer === questions[currentQuestion].answer) {
            setScore(score + 1);
        }
 
        const nextQuestion = currentQuestion + 1;
        if (nextQuestion < questions.length) {
            setCurrentQuestion(nextQuestion);
        } else {
            alert(`Quiz finished. You scored ${score}/${questions.length}`);
        }
    };
 
    return (
        <div>
            <h1 className="text-center">Quiz App</h1>
            {currentQuestion < questions.length ? (
                <Question
                    question={questions[currentQuestion].question}
                    choices={questions[currentQuestion].choices}
                    answer={questions[currentQuestion].answer}
                    onAnswer={handleAnswer}
                />
            ) : "null"
            }
        </div>
    )
}
 
export default Quiz;


Javascript




//App.tsx
import Quiz from "./components/Quiz";
import 'bootstrap/dist/css/bootstrap.min.css';
 
function App() {
    return (
        <div className="container my-5">
            <Quiz />
        </div>
    );
}
 
export default App;


Step to Run Application: Run the application using the following command from the root directory of the project:

npm start

Output:

How to build a Quiz App with React and TypeScript

Output



Like Article
Suggest improvement
Share your thoughts in the comments

Similar Reads