BeginnerCoder
advanced#react#socket.io#real-time chat

Building a Real-Time Chat Application with React and Socket.io

This article was AI-drafted and has not been reviewed yet. Spotted a mistake? Tell us.

Learn how to build a real-time chat application using React and Socket.io, including setting up the server and client-side code.

Introduction to Real-Time Chat Application

In this tutorial, we will build a real-time chat application using React and Socket.io. This application will allow users to send and receive messages in real-time.

Step 1: Setting up the Project

First, we need to set up a new React project. We can do this by running the following command in our terminal:

npx create-react-app chat-app

Step 2: Setting up the Server

Next, we need to set up a new Node.js server using Socket.io. We can do this by creating a new file called server.js in the root directory:

const express = require('express');
const app = express();
const server = require('http').createServer(app);
const io = require('socket.io')(server);

io.on('connection', socket => {
  console.log('User connected');

socket.on('message', message => {
    io.emit('message', message);
  });

socket.on('disconnect', () => {
    console.log('User disconnected');
  });
});

server.listen(3001, () => {
  console.log('Server listening on port 3001');
});

Step 3: Creating the Chat Component

We can create a new component for our chat application. We can do this by creating a new file called Chat.js in the src directory:

import React, { useState, useEffect } from 'react';
import io from 'socket.io-client';

function Chat() {
  const [messages, setMessages] = useState([]);
  const [newMessage, setNewMessage] = useState('');

const socket = io('http://localhost:3001');

useEffect(() => {
    socket.on('message', message => {
      setMessages([...messages, message]);
    });
  }, [messages]);

const handleSendMessage = () => {
    socket.emit('message', newMessage);
    setNewMessage('');
  };

return (
    <div>
      <ul>
        {messages.map((message, index) => (
          <li key={index}>{message}</li>
        ))}
      </ul>
      <input type='text' value={newMessage} onChange={(e) => setNewMessage(e.target.value)} />
      <button onClick={handleSendMessage}>Send</button>
    </div>
  );
}

export default Chat;
Keep going with react

Ready for more? Optional paid resources that pick up where this lesson leaves off.

Some links on this page are affiliate links: we may earn a commission at no extra cost to you. As an Amazon Associate I earn from qualifying purchases.