Skip to main content

Building a Real-Time Chat Application Using React and Firebase

In this step-by-step guide, I'll walk you through the process of building a chat app that allows users to send and receive messages instantly. No prior experience with Firebase or React is necessary, but a basic understanding of JavaScript and web development will be helpful. 

Overview of What We'll Cover

  1. Setting up Firebase for Real-Time Database
  2. Creating React components for the chat interface
  3. Implementing real-time message sending and receiving
  4. Handling errors gracefully in the application
  5. Ensuring a responsive design using CSS

1. Setting Up Firebase for Real-Time Database

Firebase is a powerful platform provided by Google that offers a variety of tools for building web applications, including authentication, real-time databases, and hosting. For our chat app, we'll use Firebase's Firestore (NoSQL database) to store and manage messages.

Step 1: Create a Firebase Project

  1. Go to the Firebase Console.
  2. Click on Add Project and enter your project name (e.g., "React Chat App").
  3. Click Continue, and follow the prompts to create your project.
  4. Once the project is created, click Continue to the console.

Step 2: Add Firebase to Your Web App

  1. In the Firebase dashboard, click the Web icon (</>) to register your app.
  2. Enter a nickname (e.g., "ReactChatApp").
  3. Firebase will provide you with a configuration object that you'll need later.
  4. Click Continue to Console.

Step 3: Enable Firestore Database

  1. In the Firebase Console, navigate to BuildFirestore Database.
  2. Click Create Database and choose Start in Test Mode (this allows anyone to read/write data for development purposes).
  3. Click Enable to activate Firestore.

Step 4: Install Firebase in React

  1. Open your React project folder in your terminal and run:

    npm install firebase
  2. In your project’s /src folder, create a file named firebase.js. In this file, you’ll initialize Firebase and export the database connection:

    // 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", }; const app = initializeApp(firebaseConfig); const db = getFirestore(app); export { db };

This setup ensures that you have Firebase connected to your React project.


2. Creating React Components for the Chat Interface

Now that Firebase is set up, we’ll build the chat interface using React components.

Step 1: Create the Basic Structure

Create the following components:

  • ChatWindow.js: The main chat interface that displays messages.
  • ChatMessage.js: A component to render individual messages.
  • MessageInput.js: The input field where users can type and send messages.

ChatWindow.js

This component will display all the chat messages by listening for real-time updates from Firestore:

// ChatWindow.js
import React, { useState, useEffect } from 'react'; import { collection, query, orderBy, onSnapshot } from "firebase/firestore"; import { db } from '../firebase'; import ChatMessage from './ChatMessage'; import MessageInput from './MessageInput'; function ChatWindow() { const [messages, setMessages] = useState([]); useEffect(() => { const q = query(collection(db, 'messages'), orderBy('createdAt')); const unsubscribe = onSnapshot(q, (snapshot) => { const msgs = snapshot.docs.map(doc => ({ id: doc.id, ...doc.data(), })); setMessages(msgs); }); return () => unsubscribe(); }, []); return ( <div className="chat-window"> {messages.map(msg => ( <ChatMessage key={msg.id} message={msg} /> ))} <MessageInput /> </div> ); } export default ChatWindow;

ChatMessage.js

This component displays an individual chat message. It also shows whether the message has been "sent" or "received":

// ChatMessage.js
import React from 'react'; function ChatMessage({ message }) { return ( <div className={`message ${message.status}`}> <p>{message.text}</p> <span>{message.status === 'sent' ? '✔️' : '✅'}</span> </div> ); } export default ChatMessage;

MessageInput.js

This component allows users to type and send messages. It uses Firestore to store the messages:

// MessageInput.js
import React, { useState } from 'react'; import { collection, addDoc, serverTimestamp } from "firebase/firestore"; import { db } from '../firebase'; function MessageInput() { const [text, setText] = useState(''); const sendMessage = async (e) => { e.preventDefault(); if (text.trim()) { await addDoc(collection(db, 'messages'), { text, createdAt: serverTimestamp(), status: 'sent', }); setText(''); } }; return ( <form onSubmit={sendMessage} className="message-input"> <input type="text" value={text} onChange={(e) => setText(e.target.value)} placeholder="Type a message" /> <button type="submit">Send</button> </form> ); } export default MessageInput;

3. Sending and Receiving Messages in Real-Time

The real-time functionality is handled by Firebase's onSnapshot method, which listens for updates in Firestore. Every time a new message is added, it will automatically update the UI in real time. When you submit a message using the input field, it's sent to Firestore, and Firestore triggers an update in the ChatWindow component.


4. Error Handling in the Chat Application

Error handling is crucial to provide a good user experience. Here's how you can handle errors in your app:

  • Firebase Initialization Error: In firebase.js, catch any errors that occur during Firebase initialization:

    try {
    const app = initializeApp(firebaseConfig); const db = getFirestore(app); } catch (error) { console.error("Firebase initialization error:", error); }
  • Sending Messages: Handle errors when sending a message by catching rejected promises:

    try {
    await addDoc(collection(db, 'messages'), { text, createdAt: serverTimestamp(), status: 'sent', }); setText(''); } catch (error) { console.error("Error sending message:", error); }
  • Fetching Messages: If there’s an issue while fetching messages, log it and display an error message:

    useEffect(() => {
    const q = query(collection(db, 'messages'), orderBy('createdAt')); const unsubscribe = onSnapshot( q, (snapshot) => { const msgs = snapshot.docs.map(doc => ({ id: doc.id, ...doc.data(), })); setMessages(msgs); }, (error) => { console.error("Error fetching messages:", error); } ); return () => unsubscribe(); }, []);

5. Adding Responsive Design with CSS

Make sure the chat app looks good on all screen sizes. Here’s a basic example of how to style the components:

App.css

.container {
display: flex; justify-content: center; align-items: center; height: 100vh; background-color: #f0f0f0; } .chat-window { width: 90%; max-width: 600px; height: 80vh; background-color: white; border-radius: 10px; box-shadow: 0px 4px 10px rgba(0, 0, 0, 0.1); display: flex; flex-direction: column; padding: 10px; } .message-input { display: flex; justify-content: space-between; } .message-input input { width: 80%; padding: 10px; } .message-input button { width: 15%; background-color: #007bff; color: white; border: none; cursor: pointer; } .message { padding: 10px; margin: 5px 0; border-radius: 5px; } .message.sent { background-color: #e6f7ff; } .message.received { background-color: #f0f0f0; }

This CSS ensures that the chat window is responsive and adjusts to different screen sizes.


Conclusion

Building a real-time chat application using React and Firebase is a fantastic way to learn how modern web applications handle data in real time. By following these steps, you've learned how to:

  • Set up Firebase for real-time databases.
  • Create and style React components.
  • Implement real-time message sending and receiving.
  • Add basic error handling and responsive design.

If you keep working on this project, you could extend it by adding user authentication, message timestamps, or even emojis!

Good luck, and happy coding! 🎉

You can find the code in the following github repository : https://github.com/yasdan/ReactDemos/tree/main/chatApp

Comments

Popular posts from this blog

Building a Responsive Weather App with React

 Fetching and Displaying Weather Data      By - ABDUL YESDANI Objective:  This document will help you prepare for the workshop on building a responsive weather app using React. You will learn the basics of React, how to use APIs, and how to work with data fetched from an API. By the end of the workshop, you’ll build a simple weather app that fetches real-time weather data.  1. What is React? React is a JavaScript library used to build user interfaces, especially for single-page applications. It lets you create components, which are reusable, isolated pieces of code that define a part of your user interface. Key Terms Component : Think of components as building blocks for your app. Each part of your app’s UI can be a component, like a button, form, or navigation bar. JSX : A syntax extension for JavaScript, which looks a lot like HTML. JSX is used to describe what the UI should look like. State : Data that controls what gets rendered on the screen. State can change over time, like inpu

.Net Presentation

.NET is a free, cross-platform, open source developer platform for building many different types of applications. With .NET, you can use multiple languages, editors, and libraries to build for web, mobile, desktop, games, and IoT. You can write .NET apps in C#, F#, or Visual Basic. C# is a simple, modern, object-oriented, and type-safe programming language. F# is a programming language that makes it easy to write succinct, robust, and performant code. Visual Basic is an approachable language with a simple syntax for building type-safe, object-oriented apps. You can write .NET apps in C#, F#, or Visual Basic. C# is a simple, modern, object-oriented, and type-safe programming language. F# is a programming language that makes it easy to write succinct, robust, and performant code. Visual Basic is an approachable language with a simple syntax for building type-safe, object-oriented apps.

node.js tutorial

node.js is a open source server environment. Node.js is a JavaScript runtime built on Chrome's V8 JavaScript engine. Node.js is free,it is cross platform means runs on various platforms (Windows, Linux, Unix, Mac). Node.js uses JavaScript on the server.