1. Set Up Your React Project
If you don’t already have a React project set up, you can create one using Create React App:
npx create-react-app my-chat-app
cd my-chat-app
2. Create the Chat Component
Inside your src
directory, create a new file named Chat.js
. This will be your chat component that interacts with the WebSocket server.
// src/Chat.js
import React, { useState, useEffect } from 'react';
import io from 'socket.io-client';
// Replace with the URL of your WebSocket server
const SOCKET_SERVER_URL = 'http://your-api-domain.com';
const Chat = () => {
// State to store the messages and the current input
const [messages, setMessages] = useState([]);
const [message, setMessage] = useState('');
// Initialize the socket connection
useEffect(() => {
const socket = io(SOCKET_SERVER_URL);
// Listen for incoming messages
socket.on('chat message', (msg) => {
setMessages((prevMessages) => [...prevMessages, msg]);
});
// Cleanup the socket connection when the component unmounts
return () => {
socket.disconnect();
};
}, []);
// Handle message submission
const handleSubmit = (e) => {
e.preventDefault();
if (message.trim()) {
// Emit the message to the server
const socket = io(SOCKET_SERVER_URL);
socket.emit('chat message', message);
setMessage(''); // Clear the input field
}
};
return (
<div>
<h1>Socket.io Chat</h1>
<div style={{ border: '1px solid #ddd', padding: '10px', height: '300px', overflowY: 'scroll', marginBottom: '10px' }}>
{messages.map((msg, index) => (
<div key={index}>{msg}</div>
))}
</div>
<form onSubmit={handleSubmit} style={{ display: 'flex', gap: '10px' }}>
<input
type="text"
value={message}
onChange={(e) => setMessage(e.target.value)}
placeholder="Type your message..."
autoComplete="off"
style={{ flex: '1' }}
/>
<button type="submit">Send</button>
</form>
</div>
);
};
export default Chat;
Explanation of the Code
- State Management:
messages
: Stores the chat messages received from the server.message
: Stores the current input value of the message.
- WebSocket Initialization:
useEffect
: When the component mounts, a WebSocket connection is initialized usingio(SOCKET_SERVER_URL)
.socket.on('chat message', (msg) => {...})
: Listens for incoming messages from the server and updates themessages
state.
- Cleanup:
- When the component unmounts, the WebSocket connection is closed using
socket.disconnect()
.
- When the component unmounts, the WebSocket connection is closed using
- Form Handling:
- When the form is submitted, it prevents the default action (which would reload the page), emits the
chat message
event to the WebSocket server, and clears the input field.
- When the form is submitted, it prevents the default action (which would reload the page), emits the
4. Use the Chat Component in Your App
Now, replace the content of src/App.js
with the following code to render the Chat
component:
// src/App.js
import React from 'react';
import Chat from './Chat';
function App() {
return (
<div className="App">
<Chat />
</div>
);
}
export default App;
5. Run Your React Application
Now, start your React application:
npm start
Your React app should now be running, and you can see the chat interface. It will connect to your WebSocket server at http://your-api-domain.com
.
6. CORS Consideration
Make sure your WebSocket server is configured to allow connections from the domain where your React app is hosted. If needed, update your WebSocket server with appropriate CORS settings as shown earlier.
7. Final Folder Structure
Your final project structure should look something like this:
my-chat-app/
│
├── public/
│ └── index.html
│
├── src/
│ ├── Chat.js # The chat component
│ ├── App.js # Main application component
│ ├── index.js # Entry point for React
│ └── ... # Other default files
│
└── package.json # Project dependencies and scripts