In modern web applications, real-time communication is a highly demanded feature, especially in chat applications. The ability to send and receive messages in real-time enhances the user experience, making apps more interactive and engaging.
In this tutorial, we’ll walk you through building a real-time chat application using React, Node.js, and Socket.io. Socket.io is a popular JavaScript library that enables real-time, bi-directional communication between web clients and servers.
By the end of this tutorial, you'll have a working real-time chat app where multiple users can communicate instantly.
Create a new directory for the backend and initialize the project:
mkdir real-time-chat-backend
cd real-time-chat-backend
npm init -y
Install the necessary dependencies: express, http, and socket.io:
npm install express socket.io
Create a file server.js
for setting up the server:
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);
app.get('/', (req, res) => {
res.send('Server is running');
});
io.on('connection', (socket) => {
console.log('A user connected');
// Listen for chat messages
socket.on('chat message', (msg) => {
io.emit('chat message', msg); // Emit message to all clients
});
socket.on('disconnect', () => {
console.log('A user disconnected');
});
});
server.listen(5000, () => {
console.log('Server is running on http://localhost:5000');
});
Start the backend server by running the following command:
node server.js
Create a new React app:
npx create-react-app real-time-chat-frontend
cd real-time-chat-frontend
Install Socket.io-client to communicate with the server:
npm install socket.io-client
Inside the src
folder, create a new component called Chat.js
:
import React, { useState, useEffect } from 'react';
import io from 'socket.io-client';
const socket = io('http://localhost:5000'); // Connect to the backend
const Chat = () => {
const [message, setMessage] = useState('');
const [messages, setMessages] = useState([]);
const [username, setUsername] = useState('');
useEffect(() => {
// Listen for incoming messages from the server
socket.on('chat message', (msg) => {
setMessages((prevMessages) => [...prevMessages, msg]);
});
}, []);
const sendMessage = (e) => {
e.preventDefault();
if (message.trim()) {
socket.emit('chat message', `${username}: ${message}`);
setMessage('');
}
};
return (
<div className="chat-container">
<h1>Real-Time Chat</h1>
<div className="messages">
{messages.map((msg, index) => (
<p key={index}>{msg}</p>
))}
</div>
<form onSubmit={sendMessage}>
<input
type="text"
placeholder="Enter your name"
value={username}
onChange={(e) => setUsername(e.target.value)}
required
/>
<input
type="text"
placeholder="Type a message"
value={message}
onChange={(e) => setMessage(e.target.value)}
required
/>
<button type="submit">Send</button>
</form>
</div>
);
};
export default Chat;
Style the components by adding a simple CSS in App.css
or inline styles for layout:
.chat-container {
width: 80%;
margin: 0 auto;
padding: 20px;
border: 1px solid #ccc;
border-radius: 5px;
background-color: #f9f9f9;
}
.messages {
max-height: 400px;
overflow-y: scroll;
margin-bottom: 20px;
}
input {
padding: 10px;
margin: 5px;
border: 1px solid #ccc;
border-radius: 3px;
}
button {
padding: 10px 20px;
background-color: #4CAF50;
color: white;
border: none;
border-radius: 3px;
cursor: pointer;
}
button:hover {
background-color: #45a049;
}
App.js
Update App.js
to include the Chat
component:
import React from 'react';
import './App.css';
import Chat from './Chat';
const App = () => {
return (
<div className="App">
<Chat />
</div>
);
};
export default App;
Start the React frontend by running:
npm start
To improve your real-time chat app, consider adding the following features:
Building a real-time chat app with React, Node.js, and Socket.io is a great way to understand the power of WebSockets and real-time communication. Socket.io makes it easy to implement real-time, bi-directional communication between the client and server, while React provides a dynamic user interface that updates instantly.
In this tutorial, you learned how to: