In today’s interconnected world, real-time communication is crucial. Whether it’s coordinating with remote teams, providing customer support, or simply chatting with friends, the ability to exchange messages instantly enhances collaboration and connectivity. In this blog post, I’ll walk you through the process of building a real-time chat application using React on the frontend and Node.js with Socket.IO on the backend.
Why Real-Time Chat?
Real-time chat applications allow users to exchange messages instantly, creating a seamless communication experience. They are essential in various contexts, from social networking platforms to business applications requiring quick updates and responses.
Tools and Technologies
Frontend: React
- React: A popular JavaScript library for building user interfaces.
- Material-UI: Used for UI components to ensure a clean and responsive design.
Backend: Node.js with Socket.IO
- Node.js: A runtime environment for executing JavaScript code outside of a browser.
- Socket.IO: A library that enables real-time, bidirectional, and event-based communication between clients (web browsers) and servers.
Getting Started
Setting Up the Backend
First, we set up the backend server using Node.js and Socket.IO. Here’s a snippet of how our server might look:
const express = require('express');
const http = require('http');
const socketIo = require('socket.io');
const app = express();
const server = http.createServer(app);
const io = socketIo(server);
const users = {};
io.on('connection', (socket) => {
socket.on('new-user-joined', (name) => {
users[socket.id] = name;
socket.broadcast.emit('user-joined', name);
});
socket.on('send', (message) => {
if (users[socket.id]) {
socket.broadcast.emit('receive', { message, name: users[socket.id] });
}
});
socket.on('disconnect', () => {
if (users[socket.id]) {
socket.broadcast.emit('user-left', users[socket.id]);
delete users[socket.id];
}
});
});
const PORT = process.env.PORT || 8000;
server.listen(PORT, () => {
console.log(`Server is running on port ${PORT}`);
});Building the Frontend with React
On the frontend, we use React to create a responsive and interactive user interface:
import React, { useEffect, useState, useRef } from "react";
import io from 'socket.io-client';
import { sendMessage, socket, userJoined } from "../api/client";
const ChatPage = () => {
const [inputValue, setInputValue] = useState("");
const [userName, setUserName] = useState("");
const [messages, setMessages] = useState([]);
const [askName, setAskName] = useState(true);
const nameInputRef = useRef(null);
const chatContainerRef = useRef(null);
useEffect(() => {
const handleUserJoined = (name) => {
setMessages((prevMessages) => [
...prevMessages,
{ type: "user-joined", user: name, message: `${name} has joined!!` },
]);
};
const handleMessageReceive = (data) => {
setMessages((prevMessages) => [
...prevMessages,
{ type: "message", user: data.name, message: data.message },
]);
};
const handleUserLeft = (name) => {
setMessages((prevMessages) => [
...prevMessages,
{ type: "user-joined", user: name, message: `${name} has left!!` },
]);
};
socket.on("user-joined", handleUserJoined);
socket.on("receive", handleMessageReceive);
socket.on("user-left", handleUserLeft);
return () => {
socket.off("user-joined", handleUserJoined);
socket.off("receive", handleMessageReceive);
};
}, []);
const handleInputChange = (e) => {
setInputValue(e.target.value);
};
const handleSendClick = () => {
setMessages((prevMessages) => [
...prevMessages,
{ type: "message", user: userName, message: inputValue },
]);
sendMessage(inputValue);
setInputValue("");
};
const handleFormSubmit = (event) => {
event.preventDefault();
const enteredName = nameInputRef.current.value.trim();
if (enteredName) {
setUserName(enteredName);
userJoined(enteredName);
setAskName(false);
}
};
return (
<>
{/* Render UI components */}
</>
);
};
export default ChatPage;Key Features
- Real-Time Messaging: Users can send and receive messages instantly without refreshing the page.
- User Join/Leave Notifications: Notifies users when someone joins or leaves the chat room.
- Customizable Usernames: Users can set their usernames before joining the chat.
- Responsive Design: Optimized for use on various devices, providing a consistent user experience.
Conclusion
Building a real-time chat application enhances user engagement and interaction, making it a valuable addition to any web platform. By leveraging technologies like React and Socket.IO, developers can create robust, scalable, and interactive chat experiences.
Feel free to explore and dive into the code on GitHub to see how it all works together.
For more blogs, click here.
To know about me, click here.
LinkedIn: click here.
Github: click here
