Building a CRUD App with React and Firebase: A step by step guide
Firebase is a popular backend-as-a-service (BaaS) platform that allows developers to easily add real-time database functionality to their apps. In this guide, we will show you how to build a simple CRUD (Create, Read, Update, Delete) app using React and Firebase.
1. Setting up Firebase
Before we can start building our app, we need to set up a Firebase project and create a new database. To do this, go to the Firebase website and create a new account or sign in if you already have one. Then, create a new project and select “Realtime Database” as the type of database.
Next, we need to enable read and write access to the database. In the Firebase console, go to the “Database” section and select the “Rules” tab. Update the rules to allow read and write access:
{
"rules": {
".read": true,
".write": true
}
}
2. Installing dependencies
To use Firebase in our React app, we need to install the Firebase library and the React bindings for Firebase. In your React project’s directory, run the following command to install the dependencies:
npm install firebase @react-firebase/firestore
3. Connecting to Firebase
To connect to Firebase from our React app, we need to import the Firebase library and create a new Firebase app instance with our project’s credentials. In the root of your React project, create a new file called firebase.js
and add the following code:
import firebase from 'firebase/app';
import 'firebase/firestore';
const firebaseConfig = {
apiKey: "YOUR_API_KEY",
authDomain: "YOUR_AUTH_DOMAIN",
databaseURL: "YOUR_DATABASE_URL",
projectId: "YOUR_PROJECT_ID",
storageBucket: "YOUR_STORAGE_BUCKET",
messagingSenderId: "YOUR_SENDER_ID",
appId: "YOUR_APP_ID"
};
const firebaseApp = firebase.initializeApp(firebaseConfig);
const firestore = firebaseApp.firestore();
export default firestore;
Make sure to replace the placeholder values with the credentials from your Firebase project.
4. Creating a CRUD Component
Now that we have set up Firebase and connected it to our React app, we can start building our CRUD component. We will create a new component called Crud
that will allow us to create, read, update, and delete items from the Firebase database.
import React, { useState } from "react";
import firestore from "./firebase";
function Crud() {
const [items, setItems] = useState([]);
const [newItem, setNewItem] = useState("");
const handleSubmit = async (e) => {
e.preventDefault();
await firestore.collection("items").add({ name: newItem });
setNewItem("");
getItems();
};
const getItems = async () => {
const itemsRef = await firestore.collection("items").get();
const itemsData = itemsRef.docs.map((doc) => doc.data());
setItems(itemsData);
};
const handleUpdate = async (id, name) => {
await firestore.collection("items").doc(id).update({ name });
getItems();
};
const handleDelete = async (id) => {
await firestore.collection("items").doc(id).delete();
getItems();
};
return (
<div>
<form onSubmit={handleSubmit}>
<input
type="text"
value={newItem}
onChange={(e) => setNewItem(e.target.value)}
placeholder="Add a new item"
/>
<button type="submit">Add</button>
</form>
<ul>
{items.map((item) => (
<li key={item.id}>
{item.name}
<button onClick={() => handleUpdate(item.id, item.name)}>
Edit
</button>
<button onClick={() => handleDelete(item.id)}>Delete</button>
</li>
))}
</ul>
</div>
);
}
export default Crud;
In this component, we are using the `useState` hook to manage the state of the items and the new item being added. We have a `handleSubmit` function that will add a new item to the Firebase database and then call the `getItems` function to update the state with the latest items from the database. We also have `handleUpdate` and `handleDelete` functions that allow us to update and delete items from the database.
5. Conclusion
In this guide, we have shown you how to build a simple CRUD app using React and Firebase. We covered how to set up a Firebase project, connect it to a React app, and create a CRUD component that can create, read, update, and delete items from the Firebase database. This is a basic example, and you can build upon this knowledge by adding more functionality and features to your app. Remember to check the Firebase documentation for more information and examples.