BeginnerCoder
intermediate#react#quiz app#scorekeeping

Creating a Simple Quiz App with React

This article was AI-drafted and has not been reviewed yet. Spotted a mistake? Tell us.

Learn how to create a simple quiz application using React, including displaying questions and keeping track of scores.

Introduction to Quiz App

In this tutorial, we will build a simple quiz application using React. This application will display questions and keep track of scores.

Step 1: Setting Up the Project

First, we need to set up a new React project. We can do this by running the following command in our terminal:

npx create-react-app quiz-app

Step 2: Creating the Quiz Component

Next, we need to create a new component for our quiz application. We can do this by creating a new file called Quiz.js in the src directory:

import React, { useState } from 'react';

function Quiz() {
    const [questions, setQuestions] = useState([
        { question: 'What is the capital of France?', answer: 'Paris' },
        { question: 'What is the largest planet in our solar system?', answer: 'Jupiter' }
    ]);
    const [score, setScore] = useState(0);
    const [currentQuestion, setCurrentQuestion] = useState(0);

const handleAnswer = (answer) => {
        if (answer === questions[currentQuestion].answer) {
            setScore(score + 1);
        }
        setCurrentQuestion(currentQuestion + 1);
    };

return (
        <div>
            <h1>Quiz</h1>
            {questions.map((question, index) => (
                <div key={index}>
                    <p>{question.question}</p>
                    <button onClick={() => handleAnswer('Paris')}>Paris</button>
                    <button onClick={() => handleAnswer('Jupiter')}>Jupiter</button>
                </div>
            ))}
            <p>Score: {score}</p>
        </div>
    );
}

export default Quiz;

Step 3: Rendering the Quiz Component

Finally, we need to render our Quiz component in the App.js file:

import React from 'react';
import Quiz from './Quiz';

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

export default App;
Keep going with react

Ready for more? Optional paid resources that pick up where this lesson leaves off.

Some links on this page are affiliate links: we may earn a commission at no extra cost to you. As an Amazon Associate I earn from qualifying purchases.