REACT Building a Chat Application

React Chat Application with Firebase

Create a Firebase Project

  1. Go to Firebase Console.
  2. Click “Add Project”, give it a name, and complete setup.
  3. Navigate to Project Settings > General > Your Apps.
  4. Click “Add app” → Select “Web” → Register App.
  5. Copy your Firebase config (you’ll use it in step 3).
  6. Enable Authentication:
    • Go to Authentication > Sign-in method.
    • Enable Google Sign-In.
  7. 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;
    }
  }
}

Try It Now

Install Dependencies

Run the following command inside your React project folder:

npx create-react-app chat-app
cd chat-app
npm install firebase

Try It Now

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 };

Try It Now

🔹 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;

Try It Now

Features

Google Sign-In for authentication
Real-time chat using Firestore
Displays user messages with timestamps
Auto-updating messages without refreshing the page