Building a Chat Application with React and WebSocket

Building a Chat Application with React and WebSocket

JavaScript For Kids

$ 5,00

“JavaScript Explorers: Fun and Easy Coding for Kids” is a vibrant and interactive ebook designed to introduce children to the exciting world of JavaScript programming. Through colorful illustrations, step-by-step instructions, and hands-on coding exercises, young learners will embark on a fun-filled journey to discover the fundamentals of JavaScript in a playful and engaging way. With…

Introduction:

Real-time communication has become increasingly popular in web applications, and building a chat application is a great way to learn how to implement real-time features. In this article, we’ll explore how to build a simple chat application using React for the frontend and WebSocket for real-time communication between clients and the server.

Prerequisites:

Before we begin, make sure you have Node.js and npm installed on your system.

Setting Up the Server:

First, let’s create a WebSocket server using Node.js. Create a new directory for your project and run the following commands:

mkdir chat-app
cd chat-app
npm init -y
npm install ws

Create a file named server.js and add the following code to create a WebSocket server:

const WebSocket = require('ws');

const wss = new WebSocket.Server({ port: 8080 });

wss.on('connection', function connection(ws) {
  ws.on('message', function incoming(message) {
    wss.clients.forEach(function each(client) {
      if (client !== ws && client.readyState === WebSocket.OPEN) {
        client.send(message);
      }
    });
  });
});

Setting Up the Client:

Next, let’s create a React application for the client-side. Run the following commands in your project directory:

npx create-react-app client
cd client
npm install ws

Replace the contents of src/App.js with the following code:

import React, { useState, useEffect } from 'react';
import './App.css';
import WebSocket from 'ws';

function App() {
  const [messages, setMessages] = useState([]);
  const [input, setInput] = useState('');
  const ws = new WebSocket('ws://localhost:8080');

  useEffect(() => {
    ws.onopen = () => console.log('Connected to WebSocket server');
    ws.onmessage = event => {
      setMessages([...messages, event.data]);
    };
  }, []);

  const sendMessage = () => {
    ws.send(input);
    setInput('');
  };

  return (
    <div className="App">
      <h1>Chat Application</h1>
      <div className="chat-box">
        {messages.map((message, index) => (
          <div key={index} className="message">
            {message}
          </div>
        ))}
      </div>
      <input
        type="text"
        value={input}
        onChange={e => setInput(e.target.value)}
        placeholder="Type your message..."
      />
      <button onClick={sendMessage}>Send</button>
    </div>
  );
}

export default App;

Running the Application:

To run the server, navigate to the root directory of your project and run node server.js.

To run the client, navigate to the client directory and run npm start.

You should now be able to open multiple browser tabs and see real-time messages being sent and received between them.

Conclusion:

In this article, we learned how to build a simple chat application using React for the frontend and WebSocket for real-time communication. WebSocket provides a low-latency, full-duplex communication channel between the client and server, making it ideal for building real-time applications like chat apps. With React, we were able to create a responsive and interactive user interface, allowing users to send and receive messages in real-time. This project serves as a great starting point for building more complex real-time applications and exploring the capabilities of WebSocket.


My E-Book Stores Links 👇

👉 Devoog : https://devoog.com/product-category/e-books/
👉 KDP : https://amzn.to/3Ju8JH6

#Programming #Ebooks #Kids #Coding #Children #TechEducation #STEM #ProgrammingForKids #Learning #Education #ChildrensBooks #ComputerScience #Technology #YoungLearners #CodingForKids #DigitalLearning #KidsBooks #EducationalResources #ProgrammingLanguages #FunLearning #parent #parenting #education #mom #ebook #programming #future #artificialintelligence #smart #job #python #datascience #kidsactivities #java #coding #eclipse #ai #chatgpt #tesla #machinelearning #deeplearning #chatbot #fyp #ecommerce #trending #instagood #photooftheday #picoftheday #instadaily #instalike #travel #nature #art #food #fitness #happy #motivation #explore #photography #instapic #style #life

Leave a Reply