Open In App

Create an Interactive Quiz App using React-Native?

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

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: Let us have a look at how the final output will look like.

QuizApp

Preview of the image

Prerequisites:

Approach:

A quiz app is a software application that allows users to take tests and view their quiz results to see how well they performed. In this app, we included multiple questions with each having four multiple-choice options. users can submit answers to the questions by clicking on the options shown on the screen. After the end of the test score will be shown on the screen with a retest button too.

Steps to Create React Native Application:

Step 1: Create a react native application by using this command in command prompt

React-native init QuizApp

Step 2: We are creating two components for our app to write code in efficient manner which are Quiz.js and quizData.js

Project Structure:

nativeproj

Project Structure

Example: write the code in the below files

  • App.js: This file imports the component and renders it on screen
  • Quiz.js: This file implements all the functionalities and imports quiz data
  • quizData.js: This file contains the data for the quiz

Javascript




// App.js
import React from 'react';
import { View, Text, StyleSheet } from 'react-native';
import Quiz from './components/Quiz';
 
const App = () => {
    return (
        <View style={{ flex: 1, }}>
            <Text style={styles.heading}>
                Interactive Quiz App
            </Text>
            <Quiz />
        </View>
    );
};
 
export default App;
const styles = StyleSheet.create({
    heading: {
        fontSize: 25,
        marginBottom: 30,
        marginLeft: 35,
        marginTop: 60,
        fontWeight: 'bold',
        color: 'green',
    }
 
})


Javascript




//Quiz.js
 
import React, { useState, useEffect } from 'react';
import {
    View, Text, TouchableOpacity,
    StyleSheet
} from 'react-native';
 
import { quizData } from './quizData'
 
const Quiz = () => {
    const [currentQuestion, setCurrentQuestion] =
        useState(0);
    const [score, setScore] = useState(0);
    const [quizCompleted, setQuizCompleted] =
        useState(false);
    const [timeLeft, setTimeLeft] = useState(10);
 
    useEffect(() => {
        const timer = setTimeout(() => {
            if (timeLeft > 0) {
                setTimeLeft(timeLeft - 1);
            } else {
                if (currentQuestion <
                    quizData.length - 1) {
                    setCurrentQuestion(currentQuestion + 1);
                    setTimeLeft(10);
                } else {
                    setQuizCompleted(true);
                }
            }
        }, 1000);
 
        return () => clearTimeout(timer);
    }, [currentQuestion, timeLeft]);
 
    const handleAnswer = (selectedOption) => {
        if (selectedOption ===
            quizData[currentQuestion].correctAnswer) {
            setScore(score + 1);
        }
 
        if (currentQuestion <
            quizData.length - 1) {
            setCurrentQuestion(currentQuestion + 1);
            setTimeLeft(10);
        } else {
            setQuizCompleted(true);
        }
    };
 
    const handleRetest = () => {
        setCurrentQuestion(0);
        setScore(0);
        setQuizCompleted(false);
        setTimeLeft(10);
    };
    // Display questions and answers when the quiz is completed
    const displayAnswers =
        quizData.map((question, index) => (
            <View key={index}>
                <Text style={styles.question}>
                    Question {index + 1}:
                    {quizData[index].question}
                </Text>
                <Text style={styles.correctAnswer}>
                    Correct Answer:
                    {quizData[index].correctAnswer}
                </Text>
 
            </View>
        ));
 
    return (
        <View style={styles.container}>
            {quizCompleted ? (
                <View>
                    <Text style={styles.score}>
                        Your Score: {score}
                    </Text>
                    <Text style={styles.question}>
                        Questions and Answers:
                    </Text>
                    {displayAnswers}
                    <TouchableOpacity
                        style={styles.retestButton}
                        onPress={handleRetest}>
                        <Text style={styles.buttonText}>
                            Retest
                        </Text>
                    </TouchableOpacity>
                </View>
            ) : (
                <View>
                    <Text style={styles.question}>
                        {quizData[currentQuestion].question}
                    </Text>
                    <Text style={styles.timer}>
                        Time Left: {timeLeft} sec
                    </Text>
                    {quizData[currentQuestion]
                        .options.map((option, index) => (
                            <TouchableOpacity
                                key={index}
                                style={styles.option}
                                onPress={() => handleAnswer(option)}
                            >
                                <Text style={styles.buttonText}>
                                    {option}
                                </Text>
                            </TouchableOpacity>
                        ))}
                </View>
            )}
        </View>
    );
};
 
const styles = StyleSheet.create({
    container: {
        flex: 1,
        alignItems: 'center',
    },
    question: {
        fontSize: 18,
        fontWeight: 'bold',
        marginBottom: 20,
    },
    option: {
        backgroundColor: '#DDDDDD',
        padding: 10,
        marginBottom: 10,
        alignItems: 'center',
    },
    buttonText: {
        fontSize: 16,
        fontWeight: 'bold',
    },
    score: {
        fontSize: 18,
        fontWeight: 'bold',
        marginBottom: 20,
    },
    retestButton: {
        backgroundColor: 'blue',
        padding: 10,
        alignItems: 'center',
    },
    timer: {
        fontSize: 11,
        fontWeight: 'bold',
        backgroundColor: 'yellow',
        paddingVertical: 11,
        marginRight: 120,
        borderRadius: 12,
 
    },
    correctAnswer: {
        color: 'green',
    },
 
});
export default Quiz;


Javascript




quizData.js
 
export const quizData = [
    {
        question: "What is the capital of France?",
        options: ["London", "Berlin", "Paris", "Madrid"],
        correctAnswer: "Paris",
    },
    {
        question: "What is 2 + 2?",
        options: ["3", "4", "5", "6"],
        correctAnswer: "4",
    },
    {
        question: "What is the largest ocean on Earth?",
        options: ["Pacific Ocean", "Atlantic Ocean",
                  "Indian Ocean", "Arctic Ocean"],
        correctAnswer: "Pacific Ocean",
    },
    {
        question: "What is the tallest mountain on Earth?",
        options: ["Mount Everest", "Mount Kilimanjaro",
                  "Mount Fuji", "Mount Denali"],
        correctAnswer: "Mount Everest",
    },
    {
        question: "What is the chemical symbol for water?",
        options: ["H2O", "CO2", "O2", "N2"],
        correctAnswer: "H2O",
    },
];


Steps to run the application:

Step 1: Write the below commands on terminal: depending on your Operating System

  • For IOS:
npx react-native run-ios
  • For android:
npx react-native run-android

Output:

QuizApp



Like Article
Suggest improvement
Share your thoughts in the comments

Similar Reads