, ,

Building a Real-Time Chat Application with React and Websockets

Posted by


Building a Real-Time Chat Application with React and Websockets

Introduction

Real-time chat applications have become increasingly popular in recent years, with the rise of instant messaging platforms like WhatsApp and Slack. These applications provide users with a seamless and interactive communication experience, allowing them to send and receive messages in real-time.

In this article, we will explore how to build a real-time chat application using React and Websockets. React is a popular JavaScript library for building user interfaces, while Websockets is a technology that enables real-time communication between a client and a server.

Prerequisites

Before we dive into building the chat application, there are a few prerequisites to have in place:

1. Node.js and NPM: Make sure you have Node.js and NPM installed on your machine. You can download them from the official Node.js website.

2. React: Install React globally on your machine using the command `npm install -g create-react-app`. This will allow you to create a new React application.

Setting up the React Application

1. Create a new React application using the command `create-react-app chat-app`. This will create a new directory called `chat-app` with all the necessary files and dependencies for a React application.

2. Navigate into the `chat-app` directory using `cd chat-app`.

3. Start the React development server with the command `npm start`. This will start the application on `http://localhost:3000` in your browser.

4. At this point, you should see the default React application running in your browser.

Setting up the Backend Server

In order to enable real-time communication between clients, we need to set up a backend server that can handle Websocket requests. For this article, we will be using `Node.js` and `Express` for the backend server.

1. Create a new directory called `server` in the root of your project.

2. Navigate into the `server` directory using `cd server`.

3. Initialize a new Node.js project by running `npm init -y` command.

4. Install the required dependencies by running `npm install express ws –save` command.

5. Create a new file called `server.js` in the `server` directory.

6. Open `server.js` in your preferred text editor and add the following code:

“`
const express = require(‘express’);
const WebSocket = require(‘ws’);

const app = express();

const port = 8080;

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

wss.on(‘connection’, function connection(ws) {
ws.on(‘message’, function incoming(message) {
console.log(‘received: %s’, message);
wss.clients.forEach(function each(client) {
if (client !== ws && client.readyState === WebSocket.OPEN) {
client.send(message);
}
});
});
});

app.listen(port, () => console.log(`Server listening on port ${port}!`));
“`

This code sets up an Express server on port `8080` and a Websocket server on port `8081`. The Websocket server listens for new connections and broadcasts incoming messages to all connected clients.

Integrating Websockets with React

Now that we have the backend server in place, we can integrate Websockets with our React application. We will be using the `WebSocket` API provided by browsers to establish a connection with the server.

1. Open `src/App.js` in your preferred text editor.

2. Replace the existing code in `App.js` with the following code:

“`
import React, { useState, useEffect } from ‘react’;

function App() {
const [messages, setMessages] = useState([]);
const [input, setInput] = useState(”);
const socket = new WebSocket(‘ws://localhost:8081’);

useEffect(() => {
socket.onmessage = function (event) {
setMessages((prevMessages) => […prevMessages, event.data]);
};
}, []);

const handleInput = (event) => {
setInput(event.target.value);
};

const handleSubmit = (event) => {
event.preventDefault();
socket.send(input);
setInput(”);
};

return (

{messages.map((message, index) => (

{message}

))}



);
}

export default App;
“`

This code sets up the necessary state variables in the `App` component – `messages` and `input`. It also establishes a Websocket connection to the backend server. Whenever a new message is received from the server, it is added to the `messages` state variable.

The `handleInput` function updates the `input` state variable as the user types into the input field. The `handleSubmit` function sends the current value of `input` to the server and clears the input field.

Conclusion

In this article, we have explored how to build a real-time chat application using React and Websockets. We started by setting up a React application and a backend server using Express. Then, we integrated Websockets with React to establish a real-time communication channel between clients.

This application can serve as a starting point for building more advanced chat applications with features like user authentication, private messaging, and message notifications. With the power of React and Websockets, the possibilities are endless.