Lesson 60 of 60 – Quiz in React Native
100%

Quiz in React Native

A quiz is a useful feature for educational mobile applications. React Native can be used to create interactive quiz screens where users read questions, select answers, submit their responses, and see their scores.

In this lesson, we will learn how to create the structure of a simple quiz application using React Native components, state, events, conditional rendering, and arrays.

Note: A quiz can use local questions stored in JavaScript or load questions from a backend API such as a PHP and MySQL API.

1. What is a Quiz Application?

A quiz application presents questions to the user and allows the user to select answers.

Question
   ↓
Answer Options
   ↓
Select Answer
   ↓
Submit
   ↓
Check Answer
   ↓
Display Result

2. Quiz Application Features

A React Native quiz application can include:

  • Questions
  • Multiple answer options
  • Answer selection
  • Next button
  • Previous button
  • Score calculation
  • Result screen
  • Restart quiz
  • Loading state
  • API integration

3. Creating Quiz Questions

Quiz questions can be stored inside an array of JavaScript objects.

const questions = [

    {
        id: 1,
        question:
            "What is React Native?",
        options: [
            "Mobile framework",
            "Database",
            "Operating system",
            "Browser"
        ],
        answer: "Mobile framework"
    }

];

4. Understanding Question Objects

Each question object can contain information required to display and evaluate a question.

{
    id: 1,
    question: "What is React Native?",
    options: [
        "Mobile framework",
        "Database",
        "Browser",
        "Operating system"
    ],
    answer: "Mobile framework"
}

5. Storing Current Question

The current question number can be stored using React state.

const [currentQuestion,
    setCurrentQuestion] =
    useState(0);

The value 0 represents the first question in a zero-based JavaScript array.

6. Getting the Current Question

const question =
    questions[currentQuestion];

The current question object can then be used to display the question and its options.

7. Displaying the Question

<Text>
    {question.question}
</Text>

The Text component displays the current question.

8. Displaying Answer Options

The map() method can display each answer option.

{question.options.map(
    (option, index) => (

        <Pressable
            key={index}
            onPress={() =>
                selectAnswer(option)
            }
        >

            <Text>
                {option}
            </Text>

        </Pressable>

    )
)}

9. Storing the Selected Answer

The selected answer can be stored using state.

const [selectedAnswer,
    setSelectedAnswer] =
    useState(null);

When the user selects an option:

setSelectedAnswer(option);

10. Highlighting the Selected Answer

Conditional styling can be used to visually identify the selected option.

const isSelected =
    selectedAnswer === option;

The component can use isSelected to change its appearance.

11. Creating a Score State

The score can be stored using state.

const [score, setScore] =
    useState(0);

The score can increase whenever the user gives a correct answer.

12. Checking the Answer

if (
    selectedAnswer ===
    question.answer
) {

    setScore(
        score + 1
    );

}

The selected answer is compared with the correct answer stored in the question object.

13. Moving to the Next Question

function nextQuestion() {

    setSelectedAnswer(null);

    setCurrentQuestion(
        currentQuestion + 1
    );

}

The selected answer can be cleared before displaying the next question.

14. Checking the Last Question

Before moving to the next question, check whether the current question is the final question.

if (
    currentQuestion <
    questions.length - 1
) {

    setCurrentQuestion(
        currentQuestion + 1
    );

}

15. Creating a Quiz Completion State

A separate state variable can indicate that the quiz has finished.

const [quizFinished,
    setQuizFinished] =
    useState(false);

When the last question is completed:

setQuizFinished(true);

16. Displaying the Result Screen

{quizFinished ? (

    <View>

        <Text>
            Quiz Completed
        </Text>

        <Text>
            Score: {score}
        </Text>

    </View>

) : (

    <QuizQuestion />

)}

Conditional rendering allows the application to show different content after the quiz is completed.

17. Calculating the Percentage

The percentage can be calculated from the score and total number of questions.

const percentage =
    (score / questions.length) * 100;

For example, a score of 8 out of 10 gives a percentage of 80.

18. Creating a Progress Indicator

The current question number can be displayed to show quiz progress.

<Text>
    Question {currentQuestion + 1}
    of {questions.length}
</Text>

This helps the user understand how many questions remain.

19. Adding a Previous Button

A previous button can allow users to move back through the quiz.

function previousQuestion() {

    if (currentQuestion > 0) {

        setCurrentQuestion(
            currentQuestion - 1
        );

    }

}

20. Disabling Next Without an Answer

The application can require the user to select an answer before moving forward.

<Button
    title="Next"
    disabled={
        selectedAnswer === null
    }
    onPress={nextQuestion}
/>

This prevents accidental movement to the next question.

21. Restarting the Quiz

A restart function can reset the quiz state.

function restartQuiz() {

    setCurrentQuestion(0);

    setSelectedAnswer(null);

    setScore(0);

    setQuizFinished(false);

}

22. Loading Quiz Questions from an API

Instead of storing questions locally, the application can load them from a PHP API.

const response = await fetch(
    "https://example.com/api/quiz.php"
);

const data =
    await response.json();

setQuestions(data.questions);

This allows an administrator or backend system to manage questions without changing the mobile application code.

23. Loading State for Quiz Data

const [loading, setLoading] =
    useState(true);
{loading ? (

    <ActivityIndicator />

) : (

    <QuizScreen />

)}

A loading indicator can be displayed while questions are being retrieved.

24. Handling Quiz API Errors

const [error, setError] =
    useState("");

try {

    const response =
        await fetch(
            "https://example.com/api/quiz.php"
        );

    if (!response.ok) {

        throw new Error(
            "Failed to load quiz"
        );

    }

    const data =
        await response.json();

    setQuestions(
        data.questions
    );

} catch (error) {

    setError(
        "Unable to load quiz"
    );

}

25. Creating a Reusable Question Component

A reusable component can be created for displaying one quiz question.

function QuestionCard({
    question,
    selectedAnswer,
    onSelect
}) {

    return (

        <View>

            <Text>
                {question.question}
            </Text>

            {question.options.map(
                option => (

                    <Pressable
                        key={option}
                        onPress={() =>
                            onSelect(option)
                        }
                    >

                        <Text>
                            {option}
                        </Text>

                    </Pressable>

                )
            )}

        </View>

    );

}

26. Common Quiz Application Mistakes

  • Not resetting the selected answer.
  • Moving to the next question without an answer.
  • Incorrect score calculation.
  • Not handling the final question.
  • Using the wrong array index.
  • Not displaying loading state for API data.
  • Ignoring API errors.
  • Not resetting the quiz correctly.
  • Creating unnecessary repeated components.
  • Not testing every answer option.

27. Complete Basic Quiz Logic

const [currentQuestion,
    setCurrentQuestion] =
    useState(0);

const [selectedAnswer,
    setSelectedAnswer] =
    useState(null);

const [score,
    setScore] =
    useState(0);

function submitAnswer() {

    const question =
        questions[currentQuestion];

    if (
        selectedAnswer ===
        question.answer
    ) {

        setScore(
            score + 1
        );

    }

    if (
        currentQuestion <
        questions.length - 1
    ) {

        setCurrentQuestion(
            currentQuestion + 1
        );

        setSelectedAnswer(null);

    } else {

        setQuizFinished(true);

    }

}

28. Quiz Application Best Practices

  • Keep question data organized.
  • Use reusable question components.
  • Clearly highlight the selected option.
  • Prevent submission without selecting an answer.
  • Handle the final question carefully.
  • Show quiz progress.
  • Display a clear final score.
  • Provide a restart option.
  • Handle API loading and errors.
  • Test every question and answer flow.

29. Important Quiz Concepts

Concept Purpose
Question Array Stores quiz questions
useState Stores current question, answer, score, and quiz state
Pressable Allows users to select an answer
Conditional Rendering Displays questions or results based on state
FlatList Can display larger collections of questions or results
Fetch / Axios Loads questions from an API
Score Tracks the number of correct answers
Restart Resets the quiz to its initial state

30. Complete Quiz Application Workflow

Start Quiz
    ↓
Load Questions
    ↓
Display Question
    ↓
Display Options
    ↓
Select Answer
    ↓
Submit Answer
    ↓
Check Answer
    ↓
Update Score
    ↓
More Questions?
   /       \
 Yes       No
  ↓         ↓
Next      Result
Question   Screen
            ↓
          Score
            ↓
        Restart Quiz

A quiz project combines many important React Native concepts such as state management, events, conditional rendering, reusable components, API integration, loading states, error handling, and navigation. It is an excellent project for practicing the complete mobile application development workflow.

📌 Key Points

  • Quiz questions can be stored in JavaScript arrays or loaded from an API.
  • useState can manage the current question and selected answer.
  • Pressable can be used for interactive answer options.
  • The score can be updated after checking the selected answer.
  • Conditional rendering can display the quiz or result screen.
  • A progress indicator helps users track their quiz progress.
  • The application should handle the final question correctly.
  • A restart function can reset the complete quiz.
  • PHP and MySQL can provide dynamic quiz questions through an API.
  • Loading and error states should be handled when using an API.
  • Reusable components make the quiz easier to maintain.
  • A complete quiz project combines many React Native concepts learned throughout the course.

🧠 Quick Quiz

Question: Which React Native concept can be used to store the currently selected quiz answer?