React Native (Part 8): To-Do App with Firebase Firestore
In this tutorial, you will create a simple to-do app in React Native using Firebase Cloud Firestore to store and manage data.
Prerequisites
- Basic knowledge of React Native.
- Node.js and npm installed.
- A Firebase project set up (visit Firebase Console if you don’t have one).
Project Folder Structure
Before diving into the code, here is a breakdown of the folder structure for this project:
ToDoApp/
│
├── firebase.js # Firebase configuration file
├── App.js # Main application file
│
├── assets/ # Asset files like images, fonts (if any)
│
├── node_modules/ # Automatically generated; contains dependencies
│
├── .gitignore # Specifies files to be ignored by Git
├── app.json # Application configuration
├── babel.config.js # Babel configuration
├── package.json # Project metadata and dependencies
└── package-lock.json # Automatically generated; dependency tree
Explanation of Main Files
firebase.js
: Contains Firebase setup and configuration. It initializes Firebase and exports Firestore to be used throughout the app.App.js
: The main component of the application. It handles state management and renders the UI, including adding, fetching, deleting tasks, and interacting with Firestore.
Step 1: Setting Up Your React Native Project
-
Create a new React Native project using Expo:
npx create-expo-app ToDoApp cd ToDoApp npm start
-
Install Firebase:
npm install firebase
Step 2: Setting Up Firebase
-
Go to the Firebase Console and create a new project.
-
Add a new Android or iOS app to your Firebase project:
- iOS: Download the
GoogleService-Info.plist
file and add it to the root of your project. - Android: Download the
google-services.json
file and add it to theandroid/app
directory.
- iOS: Download the
-
Create a Cloud Firestore database:
- In the Firebase Console, go to Firestore Database > Create Database.
- Choose Start in test mode (open access for development purposes).
- Select a location and click Enable.
-
Copy the Firebase SDK configuration from the Firebase Console’s project settings.
Step 3: Integrating Firebase in React Native
-
Create a file
firebase.js
in the root directory and set up Firebase:firebase.js
// firebase.js import { initializeApp } from "firebase/app"; import { getFirestore } from "firebase/firestore"; const firebaseConfig = { apiKey: "YOUR_API_KEY", authDomain: "YOUR_AUTH_DOMAIN", projectId: "YOUR_PROJECT_ID", storageBucket: "YOUR_STORAGE_BUCKET", messagingSenderId: "YOUR_MESSAGING_SENDER_ID", appId: "YOUR_APP_ID", }; // Initialize Firebase const app = initializeApp(firebaseConfig); const db = getFirestore(app); export { db };
Explanation
initializeApp
: Initializes Firebase with the project’s configuration.getFirestore
: Returns the Firestore instance, which will be used for data storage.export { db }
: Exports the Firestore instance to use in other files.
Step 4: Building the To-Do Application
-
Open
App.js
and implement the following:App.js
import React, { useState, useEffect } from "react"; import { View, TextInput, Button, FlatList, Text, TouchableOpacity, StyleSheet, } from "react-native"; import { collection, addDoc, getDocs, deleteDoc, doc, } from "firebase/firestore"; import { db } from "./firebase"; export default function App() { const [task, setTask] = useState(""); const [tasks, setTasks] = useState([]); // Fetch tasks from Firestore useEffect(() => { const fetchTasks = async () => { const querySnapshot = await getDocs(collection(db, "tasks")); const tasksList = querySnapshot.docs.map(doc => ({ ...doc.data(), id: doc.id, })); setTasks(tasksList); }; fetchTasks(); }, []); // Add a new task const addTask = async () => { if (task === "") return; try { const docRef = await addDoc(collection(db, "tasks"), { text: task }); setTasks([...tasks, { text: task, id: docRef.id }]); setTask(""); } catch (e) { console.error("Error adding task: ", e); } }; // Delete a task const deleteTask = async id => { try { await deleteDoc(doc(db, "tasks", id)); setTasks(tasks.filter(task => task.id !== id)); } catch (e) { console.error("Error deleting task: ", e); } }; return ( <View style={styles.container}> <TextInput style={styles.input} placeholder="Enter a task" value={task} onChangeText={setTask} /> <Button title="Add Task" onPress={addTask} /> <FlatList data={tasks} keyExtractor={item => item.id} renderItem={({ item }) => ( <View style={styles.taskContainer}> <Text style={styles.taskText}>{item.text}</Text> <TouchableOpacity onPress={() => deleteTask(item.id)}> <Text style={styles.deleteText}>Delete</Text> </TouchableOpacity> </View> )} /> </View> ); } const styles = StyleSheet.create({ container: { flex: 1, padding: 20, marginTop: 50, }, input: { borderWidth: 1, borderColor: "#ccc", padding: 10, marginVertical: 10, borderRadius: 5, }, taskContainer: { flexDirection: "row", justifyContent: "space-between", alignItems: "center", padding: 10, borderBottomWidth: 1, borderBottomColor: "#ccc", }, taskText: { fontSize: 18, }, deleteText: { color: "red", fontWeight: "bold", }, });
Explanation
- State Management:
task
: Tracks the input text.tasks
: Stores the list of tasks fetched from Firestore.
- Fetching Data (
useEffect
):- Fetches tasks from the Firestore
tasks
collection on component mount.
- Fetches tasks from the Firestore
- Adding a Task:
- Uses
addDoc
to add a new task to Firestore. - Updates the local state with the new task.
- Uses
- Deleting a Task:
- Uses
deleteDoc
to remove the task from Firestore by itsid
. - Filters out the deleted task from the state.
- Uses
- UI Components:
TextInput
: Takes user input for the task.Button
: Adds the task to Firestore.FlatList
: Displays the list of tasks with delete functionality.
Step 5: Running the App
- Run the app using:
npm start
- You should now see a to-do app where you can add and delete tasks, with data being stored in Firebase Cloud Firestore.
Summary
In this guide, you:
- Set up a React Native app with Firebase Firestore.
- Created a basic folder structure and understood the purpose of main files.
- Built a to-do app with features to add and delete tasks, using Firestore to store data.
- Displayed the list of tasks using React Native components like
FlatList
.
Next Steps
- Add task update functionality (edit task).
- Integrate Firebase Authentication for user-specific tasks.
- Use Firestore’s advanced querying capabilities for filtering and searching tasks.
This is the foundation of using Firebase with React Native for building a to-do app. Feel free to expand and customize it!