To integrate Firebase with a React application, follow these steps:
Create a Firebase project: Go to the Firebase console (https://console.firebase.google.com/) and create a new project. Make sure to enable Firestore or Realtime Database based on your requirements.
Install Firebase in your React project: In your React project directory, run the following command to install Firebase:
npm install firebase
import firebase from "firebase/app";
import "firebase/firestore"; // Import Firestore for Firestore database
// import "firebase/database"; // Import Realtime Database for Realtime database
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"
};
firebase.initializeApp(firebaseConfig);
export default firebase;
import React, { useEffect, useState } from "react";
import firebase from "./firebase";
const App = () => {
const [data, setData] = useState([]);
useEffect(() => {
const fetchData = async () => {
const db = firebase.firestore();
const snapshot = await db.collection("your-collection").get();
const data = snapshot.docs.map(doc => doc.data());
setData(data);
};
fetchData();
}, []);
return (
<div>
{data.map(item => (
<div key={item.id}>{item.name}</div>
))}
</div>
);
};
export default App;
That's it! Your React application is now integrated with Firebase, and you can use Firebase services in your application.