SlideShare a Scribd company logo
How to Build
Real-time Chat
App with
Express, ReactJS,
and Socket.IO?
www.bacancytechnology.com
I have always been very interested in
learning how the live user interactions in
chat applications work? Such web
applications always excite me to explore
more. To quench my thirst for knowledge, I
started reading blogs and watching
tutorials. After getting my hands on
building a chat app with Express, ReactJS,
and Socket.IO, I decided to write a blog on
it, as it was once said by Margaret Fuller, “If
you have the knowledge, let others lit their
candles in it.”
Table of Index
1. Overview
2. What is Socket.IO? And how does it
work?
3. How to build the chat app with Express,
ReactJS, and Socket.IO?
4. Conclusion
Overview
It might seem quite challenging when you
read the topic – How to build a Chat App
with Express, React, and Socket.io? This
blog will surely take care of that challenge,
and I’ll try my best to make it as simple as
possible. So, let’s take the challenge and
move ahead with a positive quote I read
somewhere –
“We don’t grow when things are easy. We
grow when we face challenges.”
Before starting the coding part, I would like
to give some preliminary information about
What is Socket.IO? You can skip this part
and head towards the coding section if
you’re familiar with Socket.IO already.
What is
Socket.IO?
And How
Does it Work?
Socket.IO was developed for real-time
communication and live user-interaction. It
was a Javascript library build in 2010. As the
documentation of Socket.IO states –
Socket.IO is a library that enables real-time,
bidirectional, and event-based
communication between the browser and
the server.
With the help of Engine.IO, Socket.IO
establishes the connection and permits
bidirectional communication between
client and server. The bidirectional
communication takes place only when the
client and server both have Socket.IO
integrated. It transfers data in various
forms, but the most likely in JSON format.
Socket.IO transfers data from the client of
the particular server to the server, and then
that server transmits it to other clients. This
is how the transfer of information takes
place.
I hope you now have a better understanding
of Socket.IO. You can visit its
documentation to start your Socket.IO
tutorial. Finally, it’s time to start coding.
How to Build
the Chat App
with Express,
ReactJS, and
Socket.IO?
I assume that you have Node.js V10 or
higher version installed on your system. If
not, then click here to install.
Starting with the basics
I’m creating here the main folder and then
initiating it using NPM-
mkdir chat-app
cd chat-app
npm init
Setting up Express Server and Socket.IO
Once you click enter for all the options,
install the Express library and Socket.IO for
handling socket connections.
npm install --save express socket.io
After installing the Express and Socket.IO
library, we will create a file to implement
our new application’s logic.
touch server.js
Now we will write the express server code
in the server.js file. Open your chat-app and
start editing it.
//server.js
let express = require('express')
let http = require('http')
let socket_IO = require('socket.io')
const PORT = 8001
let app = express()
let server = http.Server(app)
let io = socketIO(server)
io.on('connection', (socket) => {
console.log('User is connected sucessfully')
socket.on('disconnect', () => {
console.log('Sorry! User is unfortunately
disconnected')
})
})
server.listen(PORT, () => {
console.log(`Running on port ${port}.`);
});
Now, by running the below-mentioned
command, ensure the code is working as
expected.
node server.js
Your console should display – Running on
port 8001.
Close the server using ctrl+c
On hitting the URL – http:// localhost: 8001,
you won’t see anything as we still need to
work on our front-end. So far, we are a bit
done with the socket listener in our sever.js
file.
Now let’s move on to my favorite part, i.e.,
front-end.
Front-end part: React Component
We will be using create-react-app for it,
some also prefer to configure Webpack, but
that’s up to you. If you don’t have create-
react-app installed on your system, use the
below command-
npm i create-react-app
Now let’s create our React application –
create-react-app chat-app-client
cd chat-app-client
You can remove unwanted files like –
favicon.ico and logo.svg from your file
structure.
Now, as we know, Socket.IO uses
Engines.IO, due to which we need to install
Socket.IO at both client and server sides. So,
it’s time to install socket.io-client
npm i socket.io-client
Client-Server Connection
This section will see how to connect the
client with the server and enable real-time
communication between them using
sockets.
import React from 'react';
import socketClient from 'socket.io-client';
const SERVER = "http:// 127.0.0.1:8001";
function ChatApp() {
let socket_io = socketClient(SERVER);
return (
< div >
< p >Just checking if this is working!< /p
>
< /div >
);
}
export default ChatApp;
Make these necessary changes in your
server.js file so that the client listens to all
the emitted events from the backend.
//server.js
let express = require('express')
let http = require('http')
let socketIO = require('socket.io')
const PORT = 8001
let app = express()
let server = http.Server(app)
let io = socketIO(server)
const STATIC = [‘global_notif,
global_chats’];
io.on(“connection”, (socket_io) => {
console.log('User is connected
successfully');
socket_io.emit(“connection”, null);
socket_io.on(“disconnect”, () => {
console.log('Sorry! User is unfortunately
disconnected');
})
})
server.listen(PORT, () => {
console.log(`Running on port ${port}.`);
});
Due to the function socket_io_emit, events
can be emitted to the front end from the
socket connection. Keep in mind that this
transmission of data will be possible only
with recently connected clients.
Now, the web socket connection is
developed, so let’s proceed to build Chat.
How to Build Chat application?
We will have a folder named Chat, which
will consist of our Channel’s components
and the main Component of Chat. I won’t be
adding CSS files for designing; instead, I’ll
focus on the logic and components.
//Main_Chat.js
import React, { Component } from 'react';
import { Channels } from './Channels';
export class Main_Chat extends
Component {
state = {
all_channels: [
{ id: 10, name: 'John', members: 20}
]
}
render() {
return (
< div >
< Channels all_channels=
{this.state.all_channels} / >
< /div >
);
}
}
// Channels.js
import React, { Component } from 'react';
export class Channels extends Component {
render() {
let channel_list = `Sorry, No channels
available`;
if (this.props.all_channels) {
list = this.props.all_channels.map(c =>
< p > {c.name} < /p >
}
return (
< div >
{channel_list}
< /div >
);
}
}
So, we have two files here- Main_Chat.js and
Channels.js. Main_Chat.js includes the
Channels.js, which will display data related to
the channel list using the prop all_channels. We
are done with the Chat folder now, moving
ahead to create a message folder for Message
Panel. We will build two files in that folder,
namely Main_Message.js and Messages.js.
//Main_Message.js
import React, { Component } from 'react';
export class Main_Message extends
Component {
render() {
return (
< div >
< p >{this.props.senderName}< /p >
< span >{this.props.text}< /span >
< /div >
)
}
}
//Messages.js
import React, { Component } from 'react';
import { Main_Message } from
'./Main_Message';
export class Messages extends Component {
render() {
let msg_list = No messages!;
if (this.props.channel.messages) {
const { msgs } = this.props
list = msgs.channel.messages.map(msg =>
) />
}
return (
< >
< p >{msg_list}< /p >
< >
< input type="text" >
< button >Send< /button >
< />
< />
);
}
}
So far, we are done with setting up Express,
ReactJS, and Socket.IO; now, without
further ado, let’s move on to develop logic.
Logical part: Sending and Receiving
Messages
We are done with the simple interface, and I
hope you’ve managed your design too.
Moving on to focus on the logic part of how
to send and receive the messages?
How to fetch the channels?
Add the following code into your server.js
file for retrieving the current channel’s data
–
// server.js
app.get('/getAllChannels', (request,
response) => {
request.json({
all_channels: STATIC
})
});
This was for the backend side, write the
following for frontend –
// Main_Chat.js
componentDidMount() {
this.loadAllChannels();
}
loadAllChannels = async () => { fetch('http://
localhost:8001/getAllChannels').then(async
response => {
let all_data = await response.json();
this.setState({ all_channels:
all_data.channels });
})
}
Now, there’s a need for some events to be emitted
and listeners in real-time communication.
Whenever a channel is being selected, it should
call an event that will eventually be handled in
the backend. Also, the front-end has to look after
the event. The front-end should have the same
events emitted by the back-end to capture it and
vice-versa.
// Main_Chat.js
handleSelect = (channel_id) => {
this.socketIO.emit('channel-join',
channel_id)
}
render() {
const { all_channels } = this.state;
return (
< Channels all_channels=
{all_channels} onChannelSelect=
{this.handleSelect} / >
);
}
// server.js
io.on('connection', (socket_IO) => {
console.log('User is connected
successfully!');
socket_IO.emit('connection', null);
socket_IO.on('channel_join', channel_id
=> {
console.log('channel join', channel_id);
STATIC.forEach(i => {
if (i.id === channel_id) {
if (i.sockets.indexOf(socket_IO.id)
== (-1)) {
i.sockets.push(socket_IO.id);
i.members++;
io.emit('channel', c);
}
} else {
let channel_index =
i.sockets.indexOf(socket_IO.id);
if (channel_index != (-1)) {
i.sockets.splice(channel_index, 1);
i.members--;
io.emit('channel', c);
}
}
});
return channel_id;
})
});
How to send messages?
Heading towards our last section of the blog
– How to Build a Chat App with Express,
ReactJS, and Socket.IO? After establishing a
stable WebSocket connection, it’s time to
learn how to send messages over it. This
section will store the message typed in the
textbox and then send that message by
clicking Send. Open your Main_Chat.js file
and make the necessary changes.
setUpSocketIO = () => {
let socketIO = socketClient(SERVER);
socketIO.on('connection', () => {
const { channels } = this.state;
if (channels) {
this.handleSelect(channels.id);
}
});
socketIO.on('channel', channel => {
let all_channels = this.state.all_channels;
all_channels.forEach(i => {
if (i.id === channel.id) {
i.members = i.members;
}
});
this.setState({ all_channels });});
socketIO.on('message', msg => {
let all_channels = this.state.all_channels
all_channels.forEach(i => {
if (i.id === msg.channel_id) {
if (!i.messages) {
i.messages = [msg];
} else {
i.messages.push(msg);
}
}
});
this.setState({ all_channels });
});
this.socketIO = socketIO;
}
onSendingMessage = (id, msg) => {
this.socketIO.emit('send-message',
{ channel_id: id,
text: msg,
name: this.socketIO.id,
id: Date.now()
});
}
render() {
const { all_channels } = this.state;
return (
< >
< Channels all_channels={all_channels}
onChannelSelect={this.handleSelect}
/ >
< Messages onSendMessage=
{this.onSendingMessage} channel=
{all_channel} / >
< />
);
}
So, this was for the front-end part.
Implementation at the back-end is quite
simpler than this; we just have to broadcast
the messages.
socketIO.on('send-message', msg => {
io.emit('message', msg);
})
This was all about how to build a chat app
with Express, ReactJS, and Socket.IO. I hope
the purpose of landing on this blog has been
satisfied. With the combination of ReactJs
and Socket.IO, you can build brilliant
applications supporting real-time
communication.
Here at Bacancy Technology, we provide
you the best guidance for various
technologies, including ReactJs and NodeJs.
You can find the best coding practices being
followed by TDD and BDD here. If you are
looking to hire Full-Stack developer who
can help you build a chat app with Express,
ReactJS, and Socket.IO, then you have
landed on the right blog post. Get in touch
with us to fulfill your custom business
requirements.
Conclusion
Thank You

More Related Content

What's hot

Chat Application | RSD
Chat Application | RSDChat Application | RSD
Chat Application | RSD
Rajon
 
Mobile/Web App Development Project Report
Mobile/Web App Development Project ReportMobile/Web App Development Project Report
Mobile/Web App Development Project Report
Abubakr Cheema
 
The Benefits of Using React JS for Web Development!
The Benefits of Using React JS for Web Development!The Benefits of Using React JS for Web Development!
The Benefits of Using React JS for Web Development!
Baharika Sopori
 
React Native
React NativeReact Native
React Native
ASIMYILDIZ
 
Chat Application [Full Documentation]
Chat Application [Full Documentation]Chat Application [Full Documentation]
Chat Application [Full Documentation]
Rajon
 
Android Jetpack
Android Jetpack Android Jetpack
Android Jetpack
Tudor Sirbu
 
Mobile App Screens UI UX Flowcharts Proposal PowerPoint Presentation Slides
Mobile App Screens UI UX Flowcharts Proposal PowerPoint Presentation SlidesMobile App Screens UI UX Flowcharts Proposal PowerPoint Presentation Slides
Mobile App Screens UI UX Flowcharts Proposal PowerPoint Presentation Slides
SlideTeam
 
A project report on chat application
A project report on chat applicationA project report on chat application
A project report on chat applicationKumar Gaurav
 
Build RESTful API Using Express JS
Build RESTful API Using Express JSBuild RESTful API Using Express JS
Build RESTful API Using Express JS
Cakra Danu Sedayu
 
Developing with the Modern App Stack: MEAN and MERN (with Angular2 and ReactJS)
Developing with the Modern App Stack: MEAN and MERN (with Angular2 and ReactJS)Developing with the Modern App Stack: MEAN and MERN (with Angular2 and ReactJS)
Developing with the Modern App Stack: MEAN and MERN (with Angular2 and ReactJS)
MongoDB
 
Client server chat application
Client server chat applicationClient server chat application
Client server chat application
Piyush Rawat
 
Online News Portal
Online News PortalOnline News Portal
Online News Portal
Dotsilicon Limited
 
Universal React apps in Next.js
Universal React apps in Next.jsUniversal React apps in Next.js
Universal React apps in Next.js
🐕 Łukasz Ostrowski
 
Social Networking Website
Social Networking WebsiteSocial Networking Website
Social Networking Websiteguestec05a4
 
Express JS
Express JSExpress JS
Express JS
Alok Guha
 
Angular server side rendering - Strategies & Technics
Angular server side rendering - Strategies & Technics Angular server side rendering - Strategies & Technics
Angular server side rendering - Strategies & Technics
Eliran Eliassy
 
online news portal system
online news portal systemonline news portal system
online news portal system
Arman Ahmed
 
Reactjs
ReactjsReactjs
Web application presentation
Web application presentationWeb application presentation
Web application presentation
Ehsan Ullah Kakar
 

What's hot (20)

Social networking
Social networkingSocial networking
Social networking
 
Chat Application | RSD
Chat Application | RSDChat Application | RSD
Chat Application | RSD
 
Mobile/Web App Development Project Report
Mobile/Web App Development Project ReportMobile/Web App Development Project Report
Mobile/Web App Development Project Report
 
The Benefits of Using React JS for Web Development!
The Benefits of Using React JS for Web Development!The Benefits of Using React JS for Web Development!
The Benefits of Using React JS for Web Development!
 
React Native
React NativeReact Native
React Native
 
Chat Application [Full Documentation]
Chat Application [Full Documentation]Chat Application [Full Documentation]
Chat Application [Full Documentation]
 
Android Jetpack
Android Jetpack Android Jetpack
Android Jetpack
 
Mobile App Screens UI UX Flowcharts Proposal PowerPoint Presentation Slides
Mobile App Screens UI UX Flowcharts Proposal PowerPoint Presentation SlidesMobile App Screens UI UX Flowcharts Proposal PowerPoint Presentation Slides
Mobile App Screens UI UX Flowcharts Proposal PowerPoint Presentation Slides
 
A project report on chat application
A project report on chat applicationA project report on chat application
A project report on chat application
 
Build RESTful API Using Express JS
Build RESTful API Using Express JSBuild RESTful API Using Express JS
Build RESTful API Using Express JS
 
Developing with the Modern App Stack: MEAN and MERN (with Angular2 and ReactJS)
Developing with the Modern App Stack: MEAN and MERN (with Angular2 and ReactJS)Developing with the Modern App Stack: MEAN and MERN (with Angular2 and ReactJS)
Developing with the Modern App Stack: MEAN and MERN (with Angular2 and ReactJS)
 
Client server chat application
Client server chat applicationClient server chat application
Client server chat application
 
Online News Portal
Online News PortalOnline News Portal
Online News Portal
 
Universal React apps in Next.js
Universal React apps in Next.jsUniversal React apps in Next.js
Universal React apps in Next.js
 
Social Networking Website
Social Networking WebsiteSocial Networking Website
Social Networking Website
 
Express JS
Express JSExpress JS
Express JS
 
Angular server side rendering - Strategies & Technics
Angular server side rendering - Strategies & Technics Angular server side rendering - Strategies & Technics
Angular server side rendering - Strategies & Technics
 
online news portal system
online news portal systemonline news portal system
online news portal system
 
Reactjs
ReactjsReactjs
Reactjs
 
Web application presentation
Web application presentationWeb application presentation
Web application presentation
 

Similar to How to Build Real-time Chat App with Express, ReactJS, and Socket.IO?

Raisa anthony web programming 1st week
Raisa anthony   web programming 1st weekRaisa anthony   web programming 1st week
Raisa anthony web programming 1st weekRaisa Anjani
 
Building isomorphic java script apps faster with next.js
Building isomorphic java script apps faster with next.jsBuilding isomorphic java script apps faster with next.js
Building isomorphic java script apps faster with next.js
Madhav Chaturvedi
 
NodeJS @ ACS
NodeJS @ ACSNodeJS @ ACS
NodeJS @ ACS
Mauro Parra-Miranda
 
How to build a chat application with react js, nodejs, and socket.io
How to build a chat application with react js, nodejs, and socket.ioHow to build a chat application with react js, nodejs, and socket.io
How to build a chat application with react js, nodejs, and socket.io
Katy Slemon
 
The complete-beginners-guide-to-react dyrr
The complete-beginners-guide-to-react dyrrThe complete-beginners-guide-to-react dyrr
The complete-beginners-guide-to-react dyrr
AfreenK
 
Starting with Node.js
Starting with Node.jsStarting with Node.js
Starting with Node.js
Jitendra Zaa
 
Tomcat + other things
Tomcat + other thingsTomcat + other things
Tomcat + other things
Aravindharamanan S
 
How web works and browser works ? (behind the scenes)
How web works and browser works ? (behind the scenes)How web works and browser works ? (behind the scenes)
How web works and browser works ? (behind the scenes)
Vibhor Grover
 
Basic API Creation with Node.JS
Basic API Creation with Node.JSBasic API Creation with Node.JS
Basic API Creation with Node.JS
Azilen Technologies Pvt. Ltd.
 
3 Ways to Get Started with a React App in 2024.pdf
3 Ways to Get Started with a React App in 2024.pdf3 Ways to Get Started with a React App in 2024.pdf
3 Ways to Get Started with a React App in 2024.pdf
BOSC Tech Labs
 
SocketStream
SocketStreamSocketStream
SocketStream
Paul Jensen
 
Day in a life of a node.js developer
Day in a life of a node.js developerDay in a life of a node.js developer
Day in a life of a node.js developerEdureka!
 
Day In A Life Of A Node.js Developer
Day In A Life Of A Node.js DeveloperDay In A Life Of A Node.js Developer
Day In A Life Of A Node.js Developer
Edureka!
 
learn mvc project in 7 day
learn mvc project in 7 daylearn mvc project in 7 day
learn mvc project in 7 day
Quach Long
 
How to build twitter bot using golang from scratch
How to build twitter bot using golang from scratchHow to build twitter bot using golang from scratch
How to build twitter bot using golang from scratch
Katy Slemon
 
Proper Connections Development for Proper Domino Developers
Proper Connections Development for Proper Domino DevelopersProper Connections Development for Proper Domino Developers
Proper Connections Development for Proper Domino Developers
Mark Myers
 
Node js getting started
Node js getting startedNode js getting started
Node js getting started
Pallavi Srivastava
 
Building A Simple Web Service With CXF
Building A Simple Web Service With CXFBuilding A Simple Web Service With CXF
Building A Simple Web Service With CXF
Carl Lu
 

Similar to How to Build Real-time Chat App with Express, ReactJS, and Socket.IO? (20)

Raisa anthony web programming 1st week
Raisa anthony   web programming 1st weekRaisa anthony   web programming 1st week
Raisa anthony web programming 1st week
 
Building isomorphic java script apps faster with next.js
Building isomorphic java script apps faster with next.jsBuilding isomorphic java script apps faster with next.js
Building isomorphic java script apps faster with next.js
 
NodeJS @ ACS
NodeJS @ ACSNodeJS @ ACS
NodeJS @ ACS
 
How to build a chat application with react js, nodejs, and socket.io
How to build a chat application with react js, nodejs, and socket.ioHow to build a chat application with react js, nodejs, and socket.io
How to build a chat application with react js, nodejs, and socket.io
 
The complete-beginners-guide-to-react dyrr
The complete-beginners-guide-to-react dyrrThe complete-beginners-guide-to-react dyrr
The complete-beginners-guide-to-react dyrr
 
Proposal
ProposalProposal
Proposal
 
Starting with Node.js
Starting with Node.jsStarting with Node.js
Starting with Node.js
 
Tomcat + other things
Tomcat + other thingsTomcat + other things
Tomcat + other things
 
Express node js
Express node jsExpress node js
Express node js
 
How web works and browser works ? (behind the scenes)
How web works and browser works ? (behind the scenes)How web works and browser works ? (behind the scenes)
How web works and browser works ? (behind the scenes)
 
Basic API Creation with Node.JS
Basic API Creation with Node.JSBasic API Creation with Node.JS
Basic API Creation with Node.JS
 
3 Ways to Get Started with a React App in 2024.pdf
3 Ways to Get Started with a React App in 2024.pdf3 Ways to Get Started with a React App in 2024.pdf
3 Ways to Get Started with a React App in 2024.pdf
 
SocketStream
SocketStreamSocketStream
SocketStream
 
Day in a life of a node.js developer
Day in a life of a node.js developerDay in a life of a node.js developer
Day in a life of a node.js developer
 
Day In A Life Of A Node.js Developer
Day In A Life Of A Node.js DeveloperDay In A Life Of A Node.js Developer
Day In A Life Of A Node.js Developer
 
learn mvc project in 7 day
learn mvc project in 7 daylearn mvc project in 7 day
learn mvc project in 7 day
 
How to build twitter bot using golang from scratch
How to build twitter bot using golang from scratchHow to build twitter bot using golang from scratch
How to build twitter bot using golang from scratch
 
Proper Connections Development for Proper Domino Developers
Proper Connections Development for Proper Domino DevelopersProper Connections Development for Proper Domino Developers
Proper Connections Development for Proper Domino Developers
 
Node js getting started
Node js getting startedNode js getting started
Node js getting started
 
Building A Simple Web Service With CXF
Building A Simple Web Service With CXFBuilding A Simple Web Service With CXF
Building A Simple Web Service With CXF
 

More from Katy Slemon

React Alternatives Frameworks- Lightweight Javascript Libraries.pdf
React Alternatives Frameworks- Lightweight Javascript Libraries.pdfReact Alternatives Frameworks- Lightweight Javascript Libraries.pdf
React Alternatives Frameworks- Lightweight Javascript Libraries.pdf
Katy Slemon
 
Data Science Use Cases in Retail & Healthcare Industries.pdf
Data Science Use Cases in Retail & Healthcare Industries.pdfData Science Use Cases in Retail & Healthcare Industries.pdf
Data Science Use Cases in Retail & Healthcare Industries.pdf
Katy Slemon
 
How Much Does It Cost To Hire Golang Developer.pdf
How Much Does It Cost To Hire Golang Developer.pdfHow Much Does It Cost To Hire Golang Developer.pdf
How Much Does It Cost To Hire Golang Developer.pdf
Katy Slemon
 
What’s New in Flutter 3.pdf
What’s New in Flutter 3.pdfWhat’s New in Flutter 3.pdf
What’s New in Flutter 3.pdf
Katy Slemon
 
Why Use Ruby On Rails.pdf
Why Use Ruby On Rails.pdfWhy Use Ruby On Rails.pdf
Why Use Ruby On Rails.pdf
Katy Slemon
 
How Much Does It Cost To Hire Full Stack Developer In 2022.pdf
How Much Does It Cost To Hire Full Stack Developer In 2022.pdfHow Much Does It Cost To Hire Full Stack Developer In 2022.pdf
How Much Does It Cost To Hire Full Stack Developer In 2022.pdf
Katy Slemon
 
How to Implement Middleware Pipeline in VueJS.pdf
How to Implement Middleware Pipeline in VueJS.pdfHow to Implement Middleware Pipeline in VueJS.pdf
How to Implement Middleware Pipeline in VueJS.pdf
Katy Slemon
 
How to Build Laravel Package Using Composer.pdf
How to Build Laravel Package Using Composer.pdfHow to Build Laravel Package Using Composer.pdf
How to Build Laravel Package Using Composer.pdf
Katy Slemon
 
Sure Shot Ways To Improve And Scale Your Node js Performance.pdf
Sure Shot Ways To Improve And Scale Your Node js Performance.pdfSure Shot Ways To Improve And Scale Your Node js Performance.pdf
Sure Shot Ways To Improve And Scale Your Node js Performance.pdf
Katy Slemon
 
How to Develop Slack Bot Using Golang.pdf
How to Develop Slack Bot Using Golang.pdfHow to Develop Slack Bot Using Golang.pdf
How to Develop Slack Bot Using Golang.pdf
Katy Slemon
 
IoT Based Battery Management System in Electric Vehicles.pdf
IoT Based Battery Management System in Electric Vehicles.pdfIoT Based Battery Management System in Electric Vehicles.pdf
IoT Based Battery Management System in Electric Vehicles.pdf
Katy Slemon
 
Understanding Flexbox Layout in React Native.pdf
Understanding Flexbox Layout in React Native.pdfUnderstanding Flexbox Layout in React Native.pdf
Understanding Flexbox Layout in React Native.pdf
Katy Slemon
 
The Ultimate Guide to Laravel Performance Optimization in 2022.pdf
The Ultimate Guide to Laravel Performance Optimization in 2022.pdfThe Ultimate Guide to Laravel Performance Optimization in 2022.pdf
The Ultimate Guide to Laravel Performance Optimization in 2022.pdf
Katy Slemon
 
New Features in iOS 15 and Swift 5.5.pdf
New Features in iOS 15 and Swift 5.5.pdfNew Features in iOS 15 and Swift 5.5.pdf
New Features in iOS 15 and Swift 5.5.pdf
Katy Slemon
 
How to Hire & Manage Dedicated Team For Your Next Product Development.pdf
How to Hire & Manage Dedicated Team For Your Next Product Development.pdfHow to Hire & Manage Dedicated Team For Your Next Product Development.pdf
How to Hire & Manage Dedicated Team For Your Next Product Development.pdf
Katy Slemon
 
Choose the Right Battery Management System for Lithium Ion Batteries.pdf
Choose the Right Battery Management System for Lithium Ion Batteries.pdfChoose the Right Battery Management System for Lithium Ion Batteries.pdf
Choose the Right Battery Management System for Lithium Ion Batteries.pdf
Katy Slemon
 
Flutter Performance Tuning Best Practices From the Pros.pdf
Flutter Performance Tuning Best Practices From the Pros.pdfFlutter Performance Tuning Best Practices From the Pros.pdf
Flutter Performance Tuning Best Practices From the Pros.pdf
Katy Slemon
 
Angular Universal How to Build Angular SEO Friendly App.pdf
Angular Universal How to Build Angular SEO Friendly App.pdfAngular Universal How to Build Angular SEO Friendly App.pdf
Angular Universal How to Build Angular SEO Friendly App.pdf
Katy Slemon
 
How to Set Up and Send Mails Using SendGrid in NodeJs App.pdf
How to Set Up and Send Mails Using SendGrid in NodeJs App.pdfHow to Set Up and Send Mails Using SendGrid in NodeJs App.pdf
How to Set Up and Send Mails Using SendGrid in NodeJs App.pdf
Katy Slemon
 
Ruby On Rails Performance Tuning Guide.pdf
Ruby On Rails Performance Tuning Guide.pdfRuby On Rails Performance Tuning Guide.pdf
Ruby On Rails Performance Tuning Guide.pdf
Katy Slemon
 

More from Katy Slemon (20)

React Alternatives Frameworks- Lightweight Javascript Libraries.pdf
React Alternatives Frameworks- Lightweight Javascript Libraries.pdfReact Alternatives Frameworks- Lightweight Javascript Libraries.pdf
React Alternatives Frameworks- Lightweight Javascript Libraries.pdf
 
Data Science Use Cases in Retail & Healthcare Industries.pdf
Data Science Use Cases in Retail & Healthcare Industries.pdfData Science Use Cases in Retail & Healthcare Industries.pdf
Data Science Use Cases in Retail & Healthcare Industries.pdf
 
How Much Does It Cost To Hire Golang Developer.pdf
How Much Does It Cost To Hire Golang Developer.pdfHow Much Does It Cost To Hire Golang Developer.pdf
How Much Does It Cost To Hire Golang Developer.pdf
 
What’s New in Flutter 3.pdf
What’s New in Flutter 3.pdfWhat’s New in Flutter 3.pdf
What’s New in Flutter 3.pdf
 
Why Use Ruby On Rails.pdf
Why Use Ruby On Rails.pdfWhy Use Ruby On Rails.pdf
Why Use Ruby On Rails.pdf
 
How Much Does It Cost To Hire Full Stack Developer In 2022.pdf
How Much Does It Cost To Hire Full Stack Developer In 2022.pdfHow Much Does It Cost To Hire Full Stack Developer In 2022.pdf
How Much Does It Cost To Hire Full Stack Developer In 2022.pdf
 
How to Implement Middleware Pipeline in VueJS.pdf
How to Implement Middleware Pipeline in VueJS.pdfHow to Implement Middleware Pipeline in VueJS.pdf
How to Implement Middleware Pipeline in VueJS.pdf
 
How to Build Laravel Package Using Composer.pdf
How to Build Laravel Package Using Composer.pdfHow to Build Laravel Package Using Composer.pdf
How to Build Laravel Package Using Composer.pdf
 
Sure Shot Ways To Improve And Scale Your Node js Performance.pdf
Sure Shot Ways To Improve And Scale Your Node js Performance.pdfSure Shot Ways To Improve And Scale Your Node js Performance.pdf
Sure Shot Ways To Improve And Scale Your Node js Performance.pdf
 
How to Develop Slack Bot Using Golang.pdf
How to Develop Slack Bot Using Golang.pdfHow to Develop Slack Bot Using Golang.pdf
How to Develop Slack Bot Using Golang.pdf
 
IoT Based Battery Management System in Electric Vehicles.pdf
IoT Based Battery Management System in Electric Vehicles.pdfIoT Based Battery Management System in Electric Vehicles.pdf
IoT Based Battery Management System in Electric Vehicles.pdf
 
Understanding Flexbox Layout in React Native.pdf
Understanding Flexbox Layout in React Native.pdfUnderstanding Flexbox Layout in React Native.pdf
Understanding Flexbox Layout in React Native.pdf
 
The Ultimate Guide to Laravel Performance Optimization in 2022.pdf
The Ultimate Guide to Laravel Performance Optimization in 2022.pdfThe Ultimate Guide to Laravel Performance Optimization in 2022.pdf
The Ultimate Guide to Laravel Performance Optimization in 2022.pdf
 
New Features in iOS 15 and Swift 5.5.pdf
New Features in iOS 15 and Swift 5.5.pdfNew Features in iOS 15 and Swift 5.5.pdf
New Features in iOS 15 and Swift 5.5.pdf
 
How to Hire & Manage Dedicated Team For Your Next Product Development.pdf
How to Hire & Manage Dedicated Team For Your Next Product Development.pdfHow to Hire & Manage Dedicated Team For Your Next Product Development.pdf
How to Hire & Manage Dedicated Team For Your Next Product Development.pdf
 
Choose the Right Battery Management System for Lithium Ion Batteries.pdf
Choose the Right Battery Management System for Lithium Ion Batteries.pdfChoose the Right Battery Management System for Lithium Ion Batteries.pdf
Choose the Right Battery Management System for Lithium Ion Batteries.pdf
 
Flutter Performance Tuning Best Practices From the Pros.pdf
Flutter Performance Tuning Best Practices From the Pros.pdfFlutter Performance Tuning Best Practices From the Pros.pdf
Flutter Performance Tuning Best Practices From the Pros.pdf
 
Angular Universal How to Build Angular SEO Friendly App.pdf
Angular Universal How to Build Angular SEO Friendly App.pdfAngular Universal How to Build Angular SEO Friendly App.pdf
Angular Universal How to Build Angular SEO Friendly App.pdf
 
How to Set Up and Send Mails Using SendGrid in NodeJs App.pdf
How to Set Up and Send Mails Using SendGrid in NodeJs App.pdfHow to Set Up and Send Mails Using SendGrid in NodeJs App.pdf
How to Set Up and Send Mails Using SendGrid in NodeJs App.pdf
 
Ruby On Rails Performance Tuning Guide.pdf
Ruby On Rails Performance Tuning Guide.pdfRuby On Rails Performance Tuning Guide.pdf
Ruby On Rails Performance Tuning Guide.pdf
 

Recently uploaded

Mission to Decommission: Importance of Decommissioning Products to Increase E...
Mission to Decommission: Importance of Decommissioning Products to Increase E...Mission to Decommission: Importance of Decommissioning Products to Increase E...
Mission to Decommission: Importance of Decommissioning Products to Increase E...
Product School
 
Leading Change strategies and insights for effective change management pdf 1.pdf
Leading Change strategies and insights for effective change management pdf 1.pdfLeading Change strategies and insights for effective change management pdf 1.pdf
Leading Change strategies and insights for effective change management pdf 1.pdf
OnBoard
 
The Future of Platform Engineering
The Future of Platform EngineeringThe Future of Platform Engineering
The Future of Platform Engineering
Jemma Hussein Allen
 
Smart TV Buyer Insights Survey 2024 by 91mobiles.pdf
Smart TV Buyer Insights Survey 2024 by 91mobiles.pdfSmart TV Buyer Insights Survey 2024 by 91mobiles.pdf
Smart TV Buyer Insights Survey 2024 by 91mobiles.pdf
91mobiles
 
How world-class product teams are winning in the AI era by CEO and Founder, P...
How world-class product teams are winning in the AI era by CEO and Founder, P...How world-class product teams are winning in the AI era by CEO and Founder, P...
How world-class product teams are winning in the AI era by CEO and Founder, P...
Product School
 
To Graph or Not to Graph Knowledge Graph Architectures and LLMs
To Graph or Not to Graph Knowledge Graph Architectures and LLMsTo Graph or Not to Graph Knowledge Graph Architectures and LLMs
To Graph or Not to Graph Knowledge Graph Architectures and LLMs
Paul Groth
 
From Daily Decisions to Bottom Line: Connecting Product Work to Revenue by VP...
From Daily Decisions to Bottom Line: Connecting Product Work to Revenue by VP...From Daily Decisions to Bottom Line: Connecting Product Work to Revenue by VP...
From Daily Decisions to Bottom Line: Connecting Product Work to Revenue by VP...
Product School
 
Unsubscribed: Combat Subscription Fatigue With a Membership Mentality by Head...
Unsubscribed: Combat Subscription Fatigue With a Membership Mentality by Head...Unsubscribed: Combat Subscription Fatigue With a Membership Mentality by Head...
Unsubscribed: Combat Subscription Fatigue With a Membership Mentality by Head...
Product School
 
FIDO Alliance Osaka Seminar: Passkeys and the Road Ahead.pdf
FIDO Alliance Osaka Seminar: Passkeys and the Road Ahead.pdfFIDO Alliance Osaka Seminar: Passkeys and the Road Ahead.pdf
FIDO Alliance Osaka Seminar: Passkeys and the Road Ahead.pdf
FIDO Alliance
 
Kubernetes & AI - Beauty and the Beast !?! @KCD Istanbul 2024
Kubernetes & AI - Beauty and the Beast !?! @KCD Istanbul 2024Kubernetes & AI - Beauty and the Beast !?! @KCD Istanbul 2024
Kubernetes & AI - Beauty and the Beast !?! @KCD Istanbul 2024
Tobias Schneck
 
When stars align: studies in data quality, knowledge graphs, and machine lear...
When stars align: studies in data quality, knowledge graphs, and machine lear...When stars align: studies in data quality, knowledge graphs, and machine lear...
When stars align: studies in data quality, knowledge graphs, and machine lear...
Elena Simperl
 
LF Energy Webinar: Electrical Grid Modelling and Simulation Through PowSyBl -...
LF Energy Webinar: Electrical Grid Modelling and Simulation Through PowSyBl -...LF Energy Webinar: Electrical Grid Modelling and Simulation Through PowSyBl -...
LF Energy Webinar: Electrical Grid Modelling and Simulation Through PowSyBl -...
DanBrown980551
 
PHP Frameworks: I want to break free (IPC Berlin 2024)
PHP Frameworks: I want to break free (IPC Berlin 2024)PHP Frameworks: I want to break free (IPC Berlin 2024)
PHP Frameworks: I want to break free (IPC Berlin 2024)
Ralf Eggert
 
The Art of the Pitch: WordPress Relationships and Sales
The Art of the Pitch: WordPress Relationships and SalesThe Art of the Pitch: WordPress Relationships and Sales
The Art of the Pitch: WordPress Relationships and Sales
Laura Byrne
 
Dev Dives: Train smarter, not harder – active learning and UiPath LLMs for do...
Dev Dives: Train smarter, not harder – active learning and UiPath LLMs for do...Dev Dives: Train smarter, not harder – active learning and UiPath LLMs for do...
Dev Dives: Train smarter, not harder – active learning and UiPath LLMs for do...
UiPathCommunity
 
ODC, Data Fabric and Architecture User Group
ODC, Data Fabric and Architecture User GroupODC, Data Fabric and Architecture User Group
ODC, Data Fabric and Architecture User Group
CatarinaPereira64715
 
UiPath Test Automation using UiPath Test Suite series, part 4
UiPath Test Automation using UiPath Test Suite series, part 4UiPath Test Automation using UiPath Test Suite series, part 4
UiPath Test Automation using UiPath Test Suite series, part 4
DianaGray10
 
Knowledge engineering: from people to machines and back
Knowledge engineering: from people to machines and backKnowledge engineering: from people to machines and back
Knowledge engineering: from people to machines and back
Elena Simperl
 
FIDO Alliance Osaka Seminar: The WebAuthn API and Discoverable Credentials.pdf
FIDO Alliance Osaka Seminar: The WebAuthn API and Discoverable Credentials.pdfFIDO Alliance Osaka Seminar: The WebAuthn API and Discoverable Credentials.pdf
FIDO Alliance Osaka Seminar: The WebAuthn API and Discoverable Credentials.pdf
FIDO Alliance
 
Empowering NextGen Mobility via Large Action Model Infrastructure (LAMI): pav...
Empowering NextGen Mobility via Large Action Model Infrastructure (LAMI): pav...Empowering NextGen Mobility via Large Action Model Infrastructure (LAMI): pav...
Empowering NextGen Mobility via Large Action Model Infrastructure (LAMI): pav...
Thierry Lestable
 

Recently uploaded (20)

Mission to Decommission: Importance of Decommissioning Products to Increase E...
Mission to Decommission: Importance of Decommissioning Products to Increase E...Mission to Decommission: Importance of Decommissioning Products to Increase E...
Mission to Decommission: Importance of Decommissioning Products to Increase E...
 
Leading Change strategies and insights for effective change management pdf 1.pdf
Leading Change strategies and insights for effective change management pdf 1.pdfLeading Change strategies and insights for effective change management pdf 1.pdf
Leading Change strategies and insights for effective change management pdf 1.pdf
 
The Future of Platform Engineering
The Future of Platform EngineeringThe Future of Platform Engineering
The Future of Platform Engineering
 
Smart TV Buyer Insights Survey 2024 by 91mobiles.pdf
Smart TV Buyer Insights Survey 2024 by 91mobiles.pdfSmart TV Buyer Insights Survey 2024 by 91mobiles.pdf
Smart TV Buyer Insights Survey 2024 by 91mobiles.pdf
 
How world-class product teams are winning in the AI era by CEO and Founder, P...
How world-class product teams are winning in the AI era by CEO and Founder, P...How world-class product teams are winning in the AI era by CEO and Founder, P...
How world-class product teams are winning in the AI era by CEO and Founder, P...
 
To Graph or Not to Graph Knowledge Graph Architectures and LLMs
To Graph or Not to Graph Knowledge Graph Architectures and LLMsTo Graph or Not to Graph Knowledge Graph Architectures and LLMs
To Graph or Not to Graph Knowledge Graph Architectures and LLMs
 
From Daily Decisions to Bottom Line: Connecting Product Work to Revenue by VP...
From Daily Decisions to Bottom Line: Connecting Product Work to Revenue by VP...From Daily Decisions to Bottom Line: Connecting Product Work to Revenue by VP...
From Daily Decisions to Bottom Line: Connecting Product Work to Revenue by VP...
 
Unsubscribed: Combat Subscription Fatigue With a Membership Mentality by Head...
Unsubscribed: Combat Subscription Fatigue With a Membership Mentality by Head...Unsubscribed: Combat Subscription Fatigue With a Membership Mentality by Head...
Unsubscribed: Combat Subscription Fatigue With a Membership Mentality by Head...
 
FIDO Alliance Osaka Seminar: Passkeys and the Road Ahead.pdf
FIDO Alliance Osaka Seminar: Passkeys and the Road Ahead.pdfFIDO Alliance Osaka Seminar: Passkeys and the Road Ahead.pdf
FIDO Alliance Osaka Seminar: Passkeys and the Road Ahead.pdf
 
Kubernetes & AI - Beauty and the Beast !?! @KCD Istanbul 2024
Kubernetes & AI - Beauty and the Beast !?! @KCD Istanbul 2024Kubernetes & AI - Beauty and the Beast !?! @KCD Istanbul 2024
Kubernetes & AI - Beauty and the Beast !?! @KCD Istanbul 2024
 
When stars align: studies in data quality, knowledge graphs, and machine lear...
When stars align: studies in data quality, knowledge graphs, and machine lear...When stars align: studies in data quality, knowledge graphs, and machine lear...
When stars align: studies in data quality, knowledge graphs, and machine lear...
 
LF Energy Webinar: Electrical Grid Modelling and Simulation Through PowSyBl -...
LF Energy Webinar: Electrical Grid Modelling and Simulation Through PowSyBl -...LF Energy Webinar: Electrical Grid Modelling and Simulation Through PowSyBl -...
LF Energy Webinar: Electrical Grid Modelling and Simulation Through PowSyBl -...
 
PHP Frameworks: I want to break free (IPC Berlin 2024)
PHP Frameworks: I want to break free (IPC Berlin 2024)PHP Frameworks: I want to break free (IPC Berlin 2024)
PHP Frameworks: I want to break free (IPC Berlin 2024)
 
The Art of the Pitch: WordPress Relationships and Sales
The Art of the Pitch: WordPress Relationships and SalesThe Art of the Pitch: WordPress Relationships and Sales
The Art of the Pitch: WordPress Relationships and Sales
 
Dev Dives: Train smarter, not harder – active learning and UiPath LLMs for do...
Dev Dives: Train smarter, not harder – active learning and UiPath LLMs for do...Dev Dives: Train smarter, not harder – active learning and UiPath LLMs for do...
Dev Dives: Train smarter, not harder – active learning and UiPath LLMs for do...
 
ODC, Data Fabric and Architecture User Group
ODC, Data Fabric and Architecture User GroupODC, Data Fabric and Architecture User Group
ODC, Data Fabric and Architecture User Group
 
UiPath Test Automation using UiPath Test Suite series, part 4
UiPath Test Automation using UiPath Test Suite series, part 4UiPath Test Automation using UiPath Test Suite series, part 4
UiPath Test Automation using UiPath Test Suite series, part 4
 
Knowledge engineering: from people to machines and back
Knowledge engineering: from people to machines and backKnowledge engineering: from people to machines and back
Knowledge engineering: from people to machines and back
 
FIDO Alliance Osaka Seminar: The WebAuthn API and Discoverable Credentials.pdf
FIDO Alliance Osaka Seminar: The WebAuthn API and Discoverable Credentials.pdfFIDO Alliance Osaka Seminar: The WebAuthn API and Discoverable Credentials.pdf
FIDO Alliance Osaka Seminar: The WebAuthn API and Discoverable Credentials.pdf
 
Empowering NextGen Mobility via Large Action Model Infrastructure (LAMI): pav...
Empowering NextGen Mobility via Large Action Model Infrastructure (LAMI): pav...Empowering NextGen Mobility via Large Action Model Infrastructure (LAMI): pav...
Empowering NextGen Mobility via Large Action Model Infrastructure (LAMI): pav...
 

How to Build Real-time Chat App with Express, ReactJS, and Socket.IO?

  • 1. How to Build Real-time Chat App with Express, ReactJS, and Socket.IO? www.bacancytechnology.com
  • 2. I have always been very interested in learning how the live user interactions in chat applications work? Such web applications always excite me to explore more. To quench my thirst for knowledge, I started reading blogs and watching tutorials. After getting my hands on building a chat app with Express, ReactJS, and Socket.IO, I decided to write a blog on it, as it was once said by Margaret Fuller, “If you have the knowledge, let others lit their candles in it.”
  • 3. Table of Index 1. Overview 2. What is Socket.IO? And how does it work? 3. How to build the chat app with Express, ReactJS, and Socket.IO? 4. Conclusion
  • 5. It might seem quite challenging when you read the topic – How to build a Chat App with Express, React, and Socket.io? This blog will surely take care of that challenge, and I’ll try my best to make it as simple as possible. So, let’s take the challenge and move ahead with a positive quote I read somewhere – “We don’t grow when things are easy. We grow when we face challenges.” Before starting the coding part, I would like to give some preliminary information about What is Socket.IO? You can skip this part and head towards the coding section if you’re familiar with Socket.IO already.
  • 7. Socket.IO was developed for real-time communication and live user-interaction. It was a Javascript library build in 2010. As the documentation of Socket.IO states – Socket.IO is a library that enables real-time, bidirectional, and event-based communication between the browser and the server. With the help of Engine.IO, Socket.IO establishes the connection and permits bidirectional communication between client and server. The bidirectional communication takes place only when the client and server both have Socket.IO integrated. It transfers data in various forms, but the most likely in JSON format.
  • 8. Socket.IO transfers data from the client of the particular server to the server, and then that server transmits it to other clients. This is how the transfer of information takes place. I hope you now have a better understanding of Socket.IO. You can visit its documentation to start your Socket.IO tutorial. Finally, it’s time to start coding.
  • 9. How to Build the Chat App with Express, ReactJS, and Socket.IO?
  • 10. I assume that you have Node.js V10 or higher version installed on your system. If not, then click here to install. Starting with the basics I’m creating here the main folder and then initiating it using NPM- mkdir chat-app cd chat-app npm init Setting up Express Server and Socket.IO Once you click enter for all the options, install the Express library and Socket.IO for handling socket connections. npm install --save express socket.io
  • 11. After installing the Express and Socket.IO library, we will create a file to implement our new application’s logic. touch server.js Now we will write the express server code in the server.js file. Open your chat-app and start editing it.
  • 12. //server.js let express = require('express') let http = require('http') let socket_IO = require('socket.io') const PORT = 8001 let app = express() let server = http.Server(app) let io = socketIO(server) io.on('connection', (socket) => { console.log('User is connected sucessfully') socket.on('disconnect', () => { console.log('Sorry! User is unfortunately disconnected') }) }) server.listen(PORT, () => { console.log(`Running on port ${port}.`); });
  • 13. Now, by running the below-mentioned command, ensure the code is working as expected. node server.js Your console should display – Running on port 8001. Close the server using ctrl+c On hitting the URL – http:// localhost: 8001, you won’t see anything as we still need to work on our front-end. So far, we are a bit done with the socket listener in our sever.js file. Now let’s move on to my favorite part, i.e., front-end.
  • 14. Front-end part: React Component We will be using create-react-app for it, some also prefer to configure Webpack, but that’s up to you. If you don’t have create- react-app installed on your system, use the below command- npm i create-react-app Now let’s create our React application – create-react-app chat-app-client cd chat-app-client You can remove unwanted files like – favicon.ico and logo.svg from your file structure.
  • 15. Now, as we know, Socket.IO uses Engines.IO, due to which we need to install Socket.IO at both client and server sides. So, it’s time to install socket.io-client npm i socket.io-client Client-Server Connection This section will see how to connect the client with the server and enable real-time communication between them using sockets.
  • 16. import React from 'react'; import socketClient from 'socket.io-client'; const SERVER = "http:// 127.0.0.1:8001"; function ChatApp() { let socket_io = socketClient(SERVER); return ( < div > < p >Just checking if this is working!< /p > < /div > ); } export default ChatApp; Make these necessary changes in your server.js file so that the client listens to all the emitted events from the backend.
  • 17. //server.js let express = require('express') let http = require('http') let socketIO = require('socket.io') const PORT = 8001 let app = express() let server = http.Server(app) let io = socketIO(server) const STATIC = [‘global_notif, global_chats’]; io.on(“connection”, (socket_io) => { console.log('User is connected successfully'); socket_io.emit(“connection”, null); socket_io.on(“disconnect”, () => { console.log('Sorry! User is unfortunately disconnected'); }) }) server.listen(PORT, () => { console.log(`Running on port ${port}.`); });
  • 18. Due to the function socket_io_emit, events can be emitted to the front end from the socket connection. Keep in mind that this transmission of data will be possible only with recently connected clients. Now, the web socket connection is developed, so let’s proceed to build Chat. How to Build Chat application? We will have a folder named Chat, which will consist of our Channel’s components and the main Component of Chat. I won’t be adding CSS files for designing; instead, I’ll focus on the logic and components.
  • 19. //Main_Chat.js import React, { Component } from 'react'; import { Channels } from './Channels'; export class Main_Chat extends Component { state = { all_channels: [ { id: 10, name: 'John', members: 20} ] } render() { return ( < div > < Channels all_channels= {this.state.all_channels} / > < /div > ); } }
  • 20. // Channels.js import React, { Component } from 'react'; export class Channels extends Component { render() { let channel_list = `Sorry, No channels available`; if (this.props.all_channels) { list = this.props.all_channels.map(c => < p > {c.name} < /p > } return ( < div > {channel_list} < /div > ); } }
  • 21. So, we have two files here- Main_Chat.js and Channels.js. Main_Chat.js includes the Channels.js, which will display data related to the channel list using the prop all_channels. We are done with the Chat folder now, moving ahead to create a message folder for Message Panel. We will build two files in that folder, namely Main_Message.js and Messages.js. //Main_Message.js import React, { Component } from 'react'; export class Main_Message extends Component { render() { return ( < div > < p >{this.props.senderName}< /p > < span >{this.props.text}< /span > < /div > ) } }
  • 22. //Messages.js import React, { Component } from 'react'; import { Main_Message } from './Main_Message'; export class Messages extends Component { render() { let msg_list = No messages!; if (this.props.channel.messages) { const { msgs } = this.props list = msgs.channel.messages.map(msg => ) /> } return ( < > < p >{msg_list}< /p > < > < input type="text" > < button >Send< /button > < /> < /> ); } }
  • 23. So far, we are done with setting up Express, ReactJS, and Socket.IO; now, without further ado, let’s move on to develop logic. Logical part: Sending and Receiving Messages We are done with the simple interface, and I hope you’ve managed your design too. Moving on to focus on the logic part of how to send and receive the messages? How to fetch the channels? Add the following code into your server.js file for retrieving the current channel’s data –
  • 24. // server.js app.get('/getAllChannels', (request, response) => { request.json({ all_channels: STATIC }) }); This was for the backend side, write the following for frontend –
  • 25. // Main_Chat.js componentDidMount() { this.loadAllChannels(); } loadAllChannels = async () => { fetch('http:// localhost:8001/getAllChannels').then(async response => { let all_data = await response.json(); this.setState({ all_channels: all_data.channels }); }) } Now, there’s a need for some events to be emitted and listeners in real-time communication. Whenever a channel is being selected, it should call an event that will eventually be handled in the backend. Also, the front-end has to look after the event. The front-end should have the same events emitted by the back-end to capture it and vice-versa.
  • 26. // Main_Chat.js handleSelect = (channel_id) => { this.socketIO.emit('channel-join', channel_id) } render() { const { all_channels } = this.state; return ( < Channels all_channels= {all_channels} onChannelSelect= {this.handleSelect} / > ); }
  • 27. // server.js io.on('connection', (socket_IO) => { console.log('User is connected successfully!'); socket_IO.emit('connection', null); socket_IO.on('channel_join', channel_id => { console.log('channel join', channel_id); STATIC.forEach(i => { if (i.id === channel_id) { if (i.sockets.indexOf(socket_IO.id) == (-1)) { i.sockets.push(socket_IO.id); i.members++; io.emit('channel', c); } } else { let channel_index = i.sockets.indexOf(socket_IO.id);
  • 28. if (channel_index != (-1)) { i.sockets.splice(channel_index, 1); i.members--; io.emit('channel', c); } } }); return channel_id; }) });
  • 29. How to send messages? Heading towards our last section of the blog – How to Build a Chat App with Express, ReactJS, and Socket.IO? After establishing a stable WebSocket connection, it’s time to learn how to send messages over it. This section will store the message typed in the textbox and then send that message by clicking Send. Open your Main_Chat.js file and make the necessary changes.
  • 30. setUpSocketIO = () => { let socketIO = socketClient(SERVER); socketIO.on('connection', () => { const { channels } = this.state; if (channels) { this.handleSelect(channels.id); } }); socketIO.on('channel', channel => { let all_channels = this.state.all_channels; all_channels.forEach(i => { if (i.id === channel.id) { i.members = i.members; } }); this.setState({ all_channels });}); socketIO.on('message', msg => { let all_channels = this.state.all_channels all_channels.forEach(i => { if (i.id === msg.channel_id) {
  • 31. if (!i.messages) { i.messages = [msg]; } else { i.messages.push(msg); } } }); this.setState({ all_channels }); }); this.socketIO = socketIO; } onSendingMessage = (id, msg) => { this.socketIO.emit('send-message', { channel_id: id, text: msg, name: this.socketIO.id, id: Date.now() }); }
  • 32. render() { const { all_channels } = this.state; return ( < > < Channels all_channels={all_channels} onChannelSelect={this.handleSelect} / > < Messages onSendMessage= {this.onSendingMessage} channel= {all_channel} / > < /> ); }
  • 33. So, this was for the front-end part. Implementation at the back-end is quite simpler than this; we just have to broadcast the messages. socketIO.on('send-message', msg => { io.emit('message', msg); }) This was all about how to build a chat app with Express, ReactJS, and Socket.IO. I hope the purpose of landing on this blog has been satisfied. With the combination of ReactJs and Socket.IO, you can build brilliant applications supporting real-time communication.
  • 34. Here at Bacancy Technology, we provide you the best guidance for various technologies, including ReactJs and NodeJs. You can find the best coding practices being followed by TDD and BDD here. If you are looking to hire Full-Stack developer who can help you build a chat app with Express, ReactJS, and Socket.IO, then you have landed on the right blog post. Get in touch with us to fulfill your custom business requirements. Conclusion