In this tutorial, we will build a quiz app using React Native and Firebase. The quiz app will allow users to take quizzes, track their scores, and retrieve quiz data from Firebase.
Prerequisites
Before we begin, make sure you have the following installed on your machine:
- Node.js
- React Native CLI
- Firebase CLI
Step 1: Set up a new React Native project
To start, create a new React Native project using the React Native CLI. Open your terminal and run the following command:
npx react-native init QuizApp
This will create a new folder called QuizApp
with all the necessary files and dependencies.
Step 2: Install Firebase packages
Next, navigate to the project folder by running cd QuizApp
in your terminal. Then, install the necessary Firebase packages by running the following commands:
npm install --save @react-native-firebase/app
npm install --save @react-native-firebase/auth
npm install --save @react-native-firebase/database
These packages will provide us with authentication and database functionalities from Firebase.
Step 3: Configure Firebase project
To use Firebase services in your app, you need to create a Firebase project. Go to the Firebase website and create a new project. Once your project is created, navigate to the project settings and find the configuration object.
Back in your React Native project, create a new folder called config
in the root directory. Inside the config
folder, create a new file called firebaseConfig.js
and add the following code:
export default {
apiKey: "YOUR_API_KEY",
authDomain: "YOUR_AUTH_DOMAIN",
databaseURL: "YOUR_DATABASE_URL",
projectId: "YOUR_PROJECT_ID",
storageBucket: "YOUR_STORAGE_BUCKET",
messagingSenderId: "YOUR_MESSAGING_SENDER_ID",
appId: "YOUR_APP_ID",
};
Replace the YOUR_API_KEY
, YOUR_AUTH_DOMAIN
, and other placeholders with the corresponding values from your Firebase project’s configuration object.
Step 4: Set up Firebase in your app
To initialize Firebase in your app, open the App.js
file located in the QuizApp
folder, and replace the contents with the following code:
import React, { useEffect } from 'react';
import { View, Text } from 'react-native';
import { initializeApp } from '@react-native-firebase/app';
import { firebaseConfig } from './config/firebaseConfig';
const App = () => {
useEffect(() => {
initializeApp(firebaseConfig);
}, []);
return (
<View>
<Text>Welcome to Quiz App!</Text>
</View>
);
};
export default App;
This code imports the necessary dependencies, initializes Firebase using the firebaseConfig
we created earlier, and displays a welcome message in the app.
Step 5: Create authentication screens
Now let’s create the authentication screens for users to sign up and log in. Create a new folder called screens
in the root directory of your project. Inside the screens
folder, create two new files: Signup.js
and Login.js
.
In the Signup.js
file, add the following code:
import React, { useState } from 'react';
import { View, TextInput, Button } from 'react-native';
import { createUserWithEmailAndPassword } from '@react-native-firebase/auth';
const Signup = () => {
const [email, setEmail] = useState('');
const [password, setPassword] = useState('');
const handleSignup = () => {
createUserWithEmailAndPassword(email, password)
.then((userCredential) => {
// Signup successful
console.log(userCredential);
})
.catch((error) => {
// Signup failed
console.log(error);
});
};
return (
<View>
<TextInput
placeholder="Email"
onChangeText={setEmail}
value={email}
/>
<TextInput
placeholder="Password"
secureTextEntry
onChangeText={setPassword}
value={password}
/>
<Button title="Sign up" onPress={handleSignup} />
</View>
);
};
export default Signup;
In the Login.js
file, add the following code:
import React, { useState } from 'react';
import { View, TextInput, Button } from 'react-native';
import { signInWithEmailAndPassword } from '@react-native-firebase/auth';
const Login = () => {
const [email, setEmail] = useState('');
const [password, setPassword] = useState('');
const handleLogin = () => {
signInWithEmailAndPassword(email, password)
.then((userCredential) => {
// Login successful
console.log(userCredential);
})
.catch((error) => {
// Login failed
console.log(error);
});
};
return (
<View>
<TextInput
placeholder="Email"
onChangeText={setEmail}
value={email}
/>
<TextInput
placeholder="Password"
secureTextEntry
onChangeText={setPassword}
value={password}
/>
<Button title="Log in" onPress={handleLogin} />
</View>
);
};
export default Login;
These files contain the necessary code to handle user authentication using Firebase.
Step 6: Set up navigation
To allow users to navigate between screens, we’ll use the react-navigation
library. Run the following command in your terminal to install the required packages:
npm install --save @react-navigation/native @react-navigation/stack
Next, open the App.js
file and update the code as follows:
import React, { useEffect } from 'react';
import { NavigationContainer } from '@react-navigation/native';
import { createStackNavigator } from '@react-navigation/stack';
import { View, Text } from 'react-native';
import { initializeApp } from '@react-native-firebase/app';
import { firebaseConfig } from './config/firebaseConfig';
import Signup from './screens/Signup';
import Login from './screens/Login';
const Stack = createStackNavigator();
const App = () => {
useEffect(() => {
initializeApp(firebaseConfig);
}, []);
return (
<NavigationContainer>
<Stack.Navigator>
<Stack.Screen
name="Home"
component={HomeScreen}
options={{ title: 'Quiz App' }}
/>
<Stack.Screen name="Signup" component={Signup} />
<Stack.Screen name="Login" component={Login} />
</Stack.Navigator>
</NavigationContainer>
);
};
const HomeScreen = () => {
return (
<View>
<Text>Welcome to Quiz App!</Text>
</View>
);
};
export default App;
Here, we have imported the necessary dependencies for navigation, created a navigation stack with the home screen, signup screen, and login screen, and wrapped our app in the NavigationContainer
component.
Step 7: Create quiz data in Firebase database
Now let’s create some quiz data in our Firebase database. Go to the Firebase console, select your project, and navigate to Cloud Firestore. Add a new collection called quizzes
and create a few quiz documents with the following structure:
quizzes/
- quizId1/
- title: "Quiz 1"
- questions/
- questionId1/
- text: "What is 2 + 2?"
- options/
- optionId1/
- text: "1"
- isCorrect: false
- optionId2/
- text: "2"
- isCorrect: false
- optionId3/
- text: "3"
- isCorrect: false
- optionId4/
- text: "4"
- isCorrect: true
- questionId2/
- text: "What is the capital of France?"
- options/
- optionId1/
- text: "Paris"
- isCorrect: true
- optionId2/
- text: "London"
- isCorrect: false
- optionId3/
- text: "Berlin"
- isCorrect: false
- optionId4/
- text: "Rome"
- isCorrect: false
- quizId2/
- title: "Quiz 2"
- questions/
- ...
Note that you can add more quizzes and questions as needed.
Step 8: Retrieve quiz data from Firebase
To retrieve quiz data from Firebase, we’ll create a new component called QuizList.js
. In the screens
folder, create a new file called QuizList.js
and add the following code:
import React, { useEffect, useState } from 'react';
import { View, Text } from 'react-native';
import { getDatabase, ref, onValue } from "@react-native-firebase/database";
const QuizList = () => {
const [quizzes, setQuizzes] = useState([]);
useEffect(() => {
const dbRef = ref(getDatabase());
onValue(dbRef, (snapshot) => {
const data = snapshot.val();
if (data) {
const quizzesData = Object.keys(data).map((key) => {
return { id: key, ...data[key] };
});
setQuizzes(quizzesData);
}
});
return () => {
offValue(dbRef);
};
}, []);
return (
<View>
{quizzes.map((quiz) => (
<Text key={quiz.id}>{quiz.title}</Text>
))}
</View>
);
};
export default QuizList;
This component retrieves the quiz data from the Firebase database and displays the quiz titles on the screen.
Step 9: Display quizzes in the app
Finally, let’s display the list of quizzes in our app. Update the HomeScreen
component in the App.js
file as follows:
import React from 'react';
import { View } from 'react-native';
import QuizList from './screens/QuizList';
const HomeScreen = () => {
return (
<View>
<QuizList />
</View>
);
};
Now when you run your app using the command npx react-native run-android
(for Android) or npx react-native run-ios
(for iOS), you should see the list of quiz titles on the home screen.
Conclusion
In this tutorial, we have built a quiz app using React Native and Firebase. We set up Firebase in our app, created authentication screens, implemented navigation between screens, retrieved quiz data from Firebase, and displayed the quizzes in the app. You can further enhance this app by adding features like taking quizzes, tracking scores, and displaying quiz results.