Building a Chat App with React Native and Socket
Here in this blog, we are going to learn building a Chat App with React Native and Socket.
1. Setting up the project:
a) Create a new React Native project using the react-native init command.
b) Install the required dependencies: npm install socket.io-client react-native-gifted-chat
2. Create a new component for the chat screen:
import React, { useEffect, useState } from 'react'; import { GiftedChat } from 'react-native-gifted-chat'; import io from 'socket.io-client'; const ChatScreen = () => { const [messages, setMessages] = useState([]); const [socket, setSocket] = useState(null); useEffect(() => { // Connect to the Socket.IO server const newSocket = io('YOUR_SOCKET_SERVER_URL'); setSocket(newSocket); // Clean up on component unmount return () => { newSocket.disconnect(); }; }, []); useEffect(() => { if (socket) { // Listen for new messages from the server socket.on('newMessage', (newMessage) => { setMessages((prevMessages) => GiftedChat.append(prevMessages, newMessage)); }); } }, [socket]); const onSend = (newMessage) => { if (socket) { // Send the new message to the server socket.emit('sendMessage', newMessage[0]); } }; return ( <GiftedChat messages={messages} onSend={(newMessage) => onSend(newMessage)} user={{ _id: 1 }} /> ); };
export default ChatScreen;
3). n the server side (Node.js), you’ll need to handle the socket events:
const io = require('socket.io')(server); io.on('connection', (socket) => { console.log('A user connected.'); socket.on('sendMessage', (newMessage) => { // Broadcast the new message to all connected clients io.emit('newMessage', newMessage); }); socket.on('disconnect', () => { console.log('A user disconnected.'); }); });
In this example, we use the react-native-gifted-chat library to provide a ready-to-use chat interface. We establish a connection to the Socket.IO server using the socket.io-client library and handle sending and receiving messages. When the user sends a new message, it is emitted to the server with the sendMessage event. The server then broadcasts the new message to all connected clients using the newMessage event. The received messages are displayed in the chat screen using the GiftedChat component.
Remember to replace ‘YOUR_SOCKET_SERVER_URL’ with the URL of your actual Socket.IO server.
This is a basic implementation to get you started with building a chat app in React Native using Socket.IO. You can enhance it further by adding user authentication, message history, and more features based on your requirements.
4. Implementing User Authentication:
a) Create a separate component for the login screen and handle user authentication using your preferred method (e.g., username/password, OAuth, etc.).
b) Once the user is authenticated, store the user information (e.g., user ID, username) in the app’s state or a global state management solution (e.g., Redux) for future reference.
5. Enhancing the Chat Screen:
a) Modify the ChatScreen component to include the user information obtained during authentication.
b) Update the onSend function to include the user information in the message object being sent to the server. For example:
const onSend = (newMessage) => { if (socket) { const { _id, username } = user; // User information obtained during authentication const message = { ...newMessage[0], user: { _id, name: username, }, }; socket.emit('sendMessage', message); } };
6). Displaying User Information in Messages:
1. Modify the message rendering in the GiftedChat component to include the sender’s name.
<GiftedChat messages={messages} onSend={(newMessage) => onSend(newMessage)} user={{ _id: user._id }} renderUsernameOnMessage />
7). Handling Socket.IO Events:
a) Expand the server-side logic to handle additional events, such as user join/leave events and displaying online users.
b) Update the client-side code to handle these events and update the UI accordingly. For example, you can display a list of online users in the chat screen.
8). Styling and Customization:
a) Customize the appearance of the chat screen using the various styling options provided by the GiftedChat component.
b) Apply your own styling using CSS-in-JS solutions like Styled Components or create custom components for message bubbles, input toolbar, etc., to match your app’s design.
Remember to implement proper error handling, data validation, and security measures based on your specific requirements. Additionally, you can add more features like real-time typing indicators, message timestamps, image/file sharing, and message reactions to enhance the chat app further.