Quiz model
- React Native course
- Intermediate
- Lesson 42/116
- 6 min
Design the Question model and state.
Quiz model
For a quiz app you first design the data model. Each question is a Question object: id (a unique number), question (the question text), options (an array of choices), answer (the index of the correct option). These fields fully describe a question.
Example: { id: 1, question: "Capital of Turkey?", options: ["Istanbul", "Ankara", "Izmir"], answer: 1 }. Here the correct answer is "Ankara" so answer is 1 (indexes start at 0). A quiz is an array of these objects: questions = [...]. This shape makes rendering questions, checking the answer and computing the score easy. The design stays simple but it carries the core of a real quiz app.
Practice Define the questions array
Define a questions constant with 2 questions. Each question has id, question, options (3 choices) and answer. First question: { id: 1, question: "Capital of Turkey?", options: ["Istanbul", "Ankara", "Izmir"], answer: 1 }. Second question: { id: 2, question: "What is 2 + 2?", options: ["3", "4", "5"], answer: 1 }.
Starter code
// Define the questions constant
// an array of 2 questions
// each question has id, question, options and answerSample solution
const questions = [
{ id: 1, question: "Capital of Turkey?", options: ["İstanbul", "Ankara", "İzmir"], answer: 1 },
{ id: 2, question: "What is 2 + 2?", options: ["3", "4", "5"], answer: 1 }
];Why the model matters
Designing the question model makes the rest of the app easier. When questions are in an array, you move to the next question by incrementing the index, check the answer with question.answer and compute the score by counting correct answers.
This model also loads easily from a real API. If the server returns a JSON array, response.json() gives you the same shape. In the next lessons you will use this model to load questions from an API, write a quiz flow and compute the score. The foundation you lay here is the backbone of the whole project. A clean data model means a clean app.
Questions and answers
Review the lesson questions together with their answers. To test yourself, solve the lesson interactively.
1 What does the answer field of a Question hold?
{ id: 1, question: "...", options: ["...", "..."], answer: 1 }- Soru metnini
- The index of the correct option Correct answer
- The number of questions
- The question ID
Explanation: answer is the index of the correct option in options.
2 Define a Question object
const question = { id: 1, question: "Başkent?", options: ["İstanbul", "Ankara"], ____: 1 };
const question = { id: 1, question: "Başkent?", options: ["İstanbul", "Ankara"], answer: 1 };
Explanation: answer holds the index of the correct option.
3 Match the field to its role
| Term | Meaning |
|---|---|
id |
Unique number |
question |
Question text |
options |
Array of choices |
answer |
Correct index |