React & WebSocket Simple Chat App
Nadim Chowdhury
Posted on January 3, 2024
Here is an example of how you can implement a simple chat application in React using WebSocket and state management:
- Create a new React app:
npx create-react-app react-chat-app
cd react-chat-app
- Install dependencies:
Install ws
for WebSocket server on the backend:
npm install ws
- Create a WebSocket server:
Create a file named server.js
in the root directory:
const WebSocket = require('ws');
const wss = new WebSocket.Server({ port: 8000 });
wss.on('connection', (ws) => {
ws.on('message', (message) => {
wss.clients.forEach((client) => {
if (client !== ws && client.readyState === WebSocket.OPEN) {
client.send(message);
}
});
});
});
Start the WebSocket server:
node server.js
- Update
src/App.js
for the React frontend:
Replace the contents of src/App.js
with the following:
import React, { useState, useEffect } from 'react';
const App = () => {
const [messages, setMessages] = useState([]);
const [messageInput, setMessageInput] = useState('');
const [socket, setSocket] = useState(null);
useEffect(() => {
const newSocket = new WebSocket('ws://127.0.0.1:8000');
newSocket.onopen = () => {
console.log('Connected to WebSocket');
};
newSocket.onmessage = (event) => {
const newMessages = [...messages, event.data];
setMessages(newMessages);
};
setSocket(newSocket);
return () => {
newSocket.close();
};
}, [messages]);
const handleSendMessage = () => {
if (socket && messageInput.trim() !== '') {
socket.send(messageInput);
setMessageInput('');
}
};
return (
<div>
<div>
{messages.map((message, index) => (
<div key={index}>{message}</div>
))}
</div>
<div>
<input
type="text"
value={messageInput}
onChange={(e) => setMessageInput(e.target.value)}
/>
<button onClick={handleSendMessage}>Send</button>
</div>
</div>
);
};
export default App;
- Run the React app:
Start the React app:
npm start
Visit http://localhost:3000
in your browser, and you should see a simple chat interface. Open multiple tabs or browsers to simulate different users, and you should see messages broadcasted in real-time.
This example demonstrates a basic React app with WebSocket communication for real-time chat. In a real-world scenario, you may want to add user authentication, error handling, and additional features. Additionally, consider deploying the WebSocket server to a production environment for a scalable solution.
If you enjoy my content and would like to support my work, you can buy me a coffee. Your support is greatly appreciated!
Disclaimer: This content has been generated by AI.
Posted on January 3, 2024
Join Our Newsletter. No Spam, Only the good stuff.
Sign up to receive the latest update from our blog.