"I want to make a chat app with React."
Do you think real-time communication is difficult?
In fact, if you use React and communication tools such as Socket.io,A chat app that anyone can use to easily communicate in real timeYou can create it.
In this article,Sending and receiving messages, displaying them, managing sender names, and connecting to serversExplained in an easy-to-understand manner.
Includes code, and is written in a way that even elementary school students can understand, allowing you to build the finished product in one go.is.
Why build a chat app with React?
Why is chat functionality needed now?
Conclusion: Real-time connection mechanisms are required for all web services.
For example, chat is used in the following services:
- Online consultation and customer support
- Educational services and tutoring exchanges
- Internal communication tools (e.g. Slack)
- SNS, Matching Services, In-game Chat
What these have in common is thatUsers can exchange messages in real timeis.
The Ministry of Economy, Trade and Industry is also promoting DX.Introducing a means of communication with high speedWe recommend
(Reference: https://www.meti.go.jp/policy/it_policy/digital_transformation/index.html).
Combining React with real-time communicationFast and flexible chat featuresYou can implement it yourself.
React and Real-time Communication Basics
What are WebSockets and Socket.io?
Conclusion: It is a system that allows you to exchange data with the server in real time.
Normal communication is one-way: request → response.
But in chat,There should always be a two-way exchange.
For that purpose,WebSocketIn React, we made it easier to useSocket.ioThis library is often used.
1 | npm install socket.io-client |
Also, Node.js and Socket.io are required on the server side.
1 | npm install express socket.io |
Creating a chat app screen layout
Design the message input and display fields
Conclusion: A simple "name, text, and submit button" structure is enough.
The UI will be configured as follows:
- Message display area (your messages and the other person's messages are displayed)
- Text input field (form)
- Submit button
- User name setting field
1 2 3 4 5 6 7 8 9 10 11 12 13 14 | function ChatUI({ messages, sendMessage }) { const [text, setText] = useState(& #039;'); const handleSubmit = (e) => { e.preventDefault(); sendMessage(text); setText(''); }; return ( <div> <div style= "{{" border: '1px solid gray' , height: '300px' , overflowy: 'scroll' }}> {messages.map((msg, i) => ( <div key= "{i}" ><strong>{msg.user}:</strong> {msg.text}</div> ))} </div> <form onsubmit= "{handleSubmit}" action= "" > <input value= "{text}" onchange= "{(e)" > setText(e.target.value) <button type= "submit" >send</button> <input type= "hidden" name= "trp-form-language" value= "en" /></form> </div> ); } |
Implementing real-time communication with Socket.io
Connect to the server and send messages
Conclusion: Socket.ioemit
andon
You can send and receive messages just by using
1 2 3 4 5 6 7 8 | import io from & #039;socket.io-client'; const socket = io('http://localhost:4000'); // Server URL function ChatApp() { const [messages, setMessages] = useState([]); const [user, setUser] = useState('guest'); useEffect(() => { socket.on('chat-message', (msg) => { setMessages((prev) => [...prev, msg]); }); return () => socket.off('chat-message'); }, []); const sendMessage = (text) => { const msg = { user, text }; socket.emit('chat-message', msg); setMessages((prev) => [...prev, msg]); }; return ( <div> <h2>Real-time chat</h2> <input value= "{user}" onchange= "{(e)" > setUser(e.target.value)} placeholder="Enter your name" /> <chatui messages= "{messages}" sendmessage= "{sendMessage}" /> </div> ); } |
Server-side construction (Node.js)
Simple configuration with Express and Socket.io
Conclusion: You can create a real-time communication server in about 10 lines of code.
1 | const express = require( 'express' ); const app = express(); const server = require( 'http' ).createServer(app); const io = require( 'socket.io' )(server, { cors: { origin: '*' } }); io.on( 'connection' , (socket) => { console.log( 'User connected' ); socket.on( 'chat-message' , (msg) => { io.emit( 'chat-message' , msg); // Send to all clients }); }); server.listen(4000, () => { console.log('Server started on port 4000'); }); |
Improvements to the chat app
How can we make the app practical?
Adding the following features makes it even more useful:
- Display of sent time
- Sorting messages
- Add a notification section that only administrators can see
- A database connection to store past history
Completed code summary
Frontend (React)
App.js
Write the following in
(ChatApp and ChatUI are integrated into one file)
Backend (Node.js)
I just introduced server.js
You can use the contents as is.
summary
In this article, we will use React and Socket.io.How to build a real-time chat app from scratchWe explained the following.
The key points are:
- With WebSocketsTwo-way communication possible
- React state management and useEffectDynamic Screen Control
- With Socket.ioEasy implementation of real-time communication
Anyone can easily create real-time apps using this method, so please give it a try for yourself.
Related links: