React Chat Application with Firebase
Create a Firebase Project
- Go to Firebase Console.
- Click “Add Project”, give it a name, and complete setup.
- Navigate to Project Settings > General > Your Apps.
- Click “Add app” โ Select “Web” โ Register App.
- Copy your Firebase config (youโll use it in step 3).
- Enable Authentication:
- Go to Authentication > Sign-in method.
- Enable Google Sign-In.
- Set Up Firestore Database:
- Go to Firestore Database > Create Database.
- Set rules to:
rules_version = '2';
service cloud.firestore {
match /databases/{database}/documents {
match /messages/{docId} {
allow read, write: if true;
}
}
}
Install Dependencies
Run the following command inside your React project folder:
npx create-react-app chat-app cd chat-app npm install firebase
Configure Firebase (src/firebase.js)
Create a new file src/firebase.js and paste this:
import { initializeApp } from "firebase/app";
import { getAuth, GoogleAuthProvider } from "firebase/auth";
import { getFirestore } from "firebase/firestore";
const firebaseConfig = {
apiKey: "YOUR_API_KEY",
authDomain: "YOUR_PROJECT_ID.firebaseapp.com",
projectId: "YOUR_PROJECT_ID",
storageBucket: "YOUR_PROJECT_ID.appspot.com",
messagingSenderId: "YOUR_MESSAGING_SENDER_ID",
appId: "YOUR_APP_ID",
};
const app = initializeApp(firebaseConfig);
const auth = getAuth(app);
const googleProvider = new GoogleAuthProvider();
const db = getFirestore(app);
export { auth, googleProvider, db };
๐น Replace YOUR_API_KEY, YOUR_PROJECT_ID, etc. with actual Firebase values.
Implement Chat Logic in src/App.js
Replace src/App.js with:
import React, { useState, useEffect } from "react";
import { auth, googleProvider, db } from "./firebase";
import { signInWithPopup, signOut } from "firebase/auth";
import { collection, addDoc, query, orderBy, onSnapshot, serverTimestamp } from "firebase/firestore";
function App() {
const [user, setUser] = useState(null);
const [messages, setMessages] = useState([]);
const [newMessage, setNewMessage] = useState("");
useEffect(() => {
const q = query(collection(db, "messages"), orderBy("timestamp"));
const unsubscribe = onSnapshot(q, (snapshot) => {
setMessages(snapshot.docs.map(doc => ({ id: doc.id, ...doc.data() })));
});
return unsubscribe;
}, []);
const signInWithGoogle = async () => {
try {
const result = await signInWithPopup(auth, googleProvider);
setUser(result.user);
} catch (error) {
console.error(error.message);
}
};
const handleSendMessage = async () => {
if (newMessage.trim()) {
await addDoc(collection(db, "messages"), {
text: newMessage,
user: user.displayName,
userPhoto: user.photoURL,
timestamp: serverTimestamp(),
});
setNewMessage("");
}
};
return (
<div style={{ textAlign: "center", marginTop: "50px" }}>
<h1>๐ฌ React Chat App</h1>
{user ? (
<>
<button onClick={() => signOut(auth)}>Logout</button>
<div style={{ maxWidth: "400px", margin: "20px auto", textAlign: "left" }}>
{messages.map((msg) => (
<div key={msg.id} style={{ padding: "10px", borderBottom: "1px solid #ddd" }}>
<img src={msg.userPhoto} alt="Avatar" style={{ width: "30px", borderRadius: "50%" }} />
<strong>{msg.user}:</strong> {msg.text}
</div>
))}
</div>
<input
type="text"
value={newMessage}
onChange={(e) => setNewMessage(e.target.value)}
placeholder="Type a message..."
/>
<button onClick={handleSendMessage}>Send</button>
</>
) : (
<button onClick={signInWithGoogle}>Sign in with Google</button>
)}
</div>
);
}
export default App;
Features
โ Google Sign-In for authentication
โ Real-time chat using Firestore
โ Displays user messages with timestamps
โ Auto-updating messages without refreshing the page