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.
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
A React Native quiz application can include:
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"
}
];
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"
}
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.
const question =
questions[currentQuestion];
The current question object can then be used to display the question and its options.
<Text>
{question.question}
</Text>
The Text component displays the current question.
The map() method can display each answer option.
{question.options.map(
(option, index) => (
<Pressable
key={index}
onPress={() =>
selectAnswer(option)
}
>
<Text>
{option}
</Text>
</Pressable>
)
)}
The selected answer can be stored using state.
const [selectedAnswer,
setSelectedAnswer] =
useState(null);
When the user selects an option:
setSelectedAnswer(option);
Conditional styling can be used to visually identify the selected option.
const isSelected =
selectedAnswer === option;
The component can use isSelected to change its appearance.
The score can be stored using state.
const [score, setScore] =
useState(0);
The score can increase whenever the user gives a correct answer.
if (
selectedAnswer ===
question.answer
) {
setScore(
score + 1
);
}
The selected answer is compared with the correct answer stored in the question object.
function nextQuestion() {
setSelectedAnswer(null);
setCurrentQuestion(
currentQuestion + 1
);
}
The selected answer can be cleared before displaying the next question.
Before moving to the next question, check whether the current question is the final question.
if (
currentQuestion <
questions.length - 1
) {
setCurrentQuestion(
currentQuestion + 1
);
}
A separate state variable can indicate that the quiz has finished.
const [quizFinished,
setQuizFinished] =
useState(false);
When the last question is completed:
setQuizFinished(true);
{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.
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.
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.
A previous button can allow users to move back through the quiz.
function previousQuestion() {
if (currentQuestion > 0) {
setCurrentQuestion(
currentQuestion - 1
);
}
}
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.
A restart function can reset the quiz state.
function restartQuiz() {
setCurrentQuestion(0);
setSelectedAnswer(null);
setScore(0);
setQuizFinished(false);
}
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.
const [loading, setLoading] =
useState(true);
{loading ? (
<ActivityIndicator />
) : (
<QuizScreen />
)}
A loading indicator can be displayed while questions are being retrieved.
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"
);
}
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>
);
}
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);
}
}
| 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 |
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.
Question: Which React Native concept can be used to store the currently selected quiz answer?