React & WebSocket Simple Chat App

nadim_ch0wdhury

Nadim Chowdhury

Posted on January 3, 2024

React & WebSocket Simple Chat App

Here is an example of how you can implement a simple chat application in React using WebSocket and state management:

  1. Create a new React app:
   npx create-react-app react-chat-app
   cd react-chat-app
Enter fullscreen mode Exit fullscreen mode
  1. Install dependencies:

Install ws for WebSocket server on the backend:

   npm install ws
Enter fullscreen mode Exit fullscreen mode
  1. 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);
         }
       });
     });
   });
Enter fullscreen mode Exit fullscreen mode

Start the WebSocket server:

   node server.js
Enter fullscreen mode Exit fullscreen mode
  1. 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;
Enter fullscreen mode Exit fullscreen mode
  1. Run the React app:

Start the React app:

   npm start
Enter fullscreen mode Exit fullscreen mode

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.

💖 💪 🙅 🚩
nadim_ch0wdhury
Nadim Chowdhury

Posted on January 3, 2024

Join Our Newsletter. No Spam, Only the good stuff.

Sign up to receive the latest update from our blog.

Related

What was your win this week?
weeklyretro What was your win this week?

November 29, 2024

Where GitOps Meets ClickOps
devops Where GitOps Meets ClickOps

November 29, 2024

How to Use KitOps with MLflow
beginners How to Use KitOps with MLflow

November 29, 2024

Modern C++ for LeetCode 🧑‍💻🚀
leetcode Modern C++ for LeetCode 🧑‍💻🚀

November 29, 2024