Building a Chat App with Socket.IO and React Native

Building a Chat App with Socket.IO and React Native

This tutorial will walk you through the steps of building a basic chat application with React Native and Socket.IO. We will be using the Expo client, React Navigation, and Node.js to create a real-time chat application.

What is SocketIO?

Socket.IO is a JavaScript library that enables real-time, bi-directional communication between web clients and servers. It has two parts: a client-side library that runs in the browser and a server-side library for Node.js. It works on every platform, browser or device, focusing equally on reliability and speed.

Prerequisites

Before you begin, you will need to have a basic understanding of React Native, Node.js and npm. You will also need to have Node.js and npm installed on your computer.

Setting up the React Native Project

To get started, we will be using the Expo client to create a new React Native project. The Expo client is a command line tool that allows you to create, build, and run React Native apps.

To install the Expo client, open a terminal window and run the following command:

npm install -g expo-cli

Once the installation is complete, you can create a new project by running the following command:

expo init my-chat-app

This will create a new React Native project in the my-chat-app directory.

Installing Expo

Next, we will need to install the Expo client. To do this, navigate to the my-chat-app directory and run the following command:

expo install

This will install the Expo client and all of its dependencies.

Installing Client

We will also need to install the client libraries for Socket.IO. To do this, run the following command:

npm install socket.io-client

This will install the Socket.IO client library and its dependencies.

Installing React Navigation

We will also need to install the React Navigation library. To do this, run the following command:

npm install @react-navigation/native

This will install the React Navigation library and its dependencies.

Building The Chat App UI

Once the Expo client and the necessary libraries are installed, we can begin building the UI for the chat application. To do this, open the App.js file in your text editor.

First, we will need to import the necessary libraries. Add the following code to the top of the file:

import React from 'react';
import { StyleSheet, Text, View } from 'react-native';
import { createStackNavigator } from '@react-navigation/native';
import SocketIOClient from 'socket.io-client';

Next, we will create a StackNavigator to manage the routing of our application. Add the following code to the App.js file:

const Stack = createStackNavigator();

export default function App() {
  return (
    <NavigationContainer>
      <Stack.Navigator>
        <Stack.Screen 
          name="Home" 
          component={HomeScreen} 
        />
        <Stack.Screen 
          name="Chat" 
          component={ChatScreen} 
        />
      </Stack.Navigator>
    </NavigationContainer>
  );
}

This will create a StackNavigator with two screens: HomeScreen and ChatScreen.

We will also need to create the HomeScreen and ChatScreen components. Add the following code to the App.js file:

const HomeScreen = () => (
  <View style={styles.container}>
    <Text>Home Screen</Text>
  </View>
);

const ChatScreen = () => (
  <View style={styles.container}>
    <Text>Chat Screen</Text>
  </View>
);

This will create the two screens for our application.

Building the NodeJS Express Server for Chat

Now that we have the UI set up, we can begin building the Node.js Express server for the chat application. To do this, we will need to create a new Node.js project and install the necessary dependencies.

Setting up the Express NodeJS Project

First, we will need to create a new Node.js project. To do this, open a terminal window and run the following command:

npm init

This will create a new package.json file in the current directory.

Installing Dependencies

Next, we will need to install the necessary dependencies for the project. To do this, run the following commands:

npm install express
npm install socket.io

This will install the Express and Socket.IO libraries and their dependencies.

Coding the Chat Functions

Now that we have the necessary libraries installed, we can begin coding the chat functions. To do this, open the index.js file in your text editor and add the following code:

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

app.get('/', function(req, res){
  res.sendFile(__dirname + '/index.html');
});

io.on('connection', function(socket){
  console.log('a user connected');
  socket.on('chat message', function(msg){
    console.log('message: ' + msg);
    io.emit('chat message', msg);
  });
});

server.listen(3000, function(){
  console.log('listening on *:3000');
});

This code sets up an Express server and a Socket.IO connection. It also defines a chat message event handler that will broadcast the message to all connected clients.

Integrate React Native & SocketIO with Chat Backend

Now that we have the server set up, we can begin integrating the React Native application with the Socket.IO server. To do this, open the App.js file in your text editor and add the following code:

const socket = SocketIOClient('http://localhost:3000');

socket.on('connect', () => {
  console.log('Connected to server');
});

socket.on('disconnect', () => {
  console.log('Disconnected from server');
});

socket.on('chat message', (msg) => {
  console.log('New message:', msg);
});

const sendMessage = (msg) => {
  socket.emit('chat message', msg);
};

This code sets up a Socket.IO connection to the server and defines event handlers for the connect, disconnect, and chat message events. It also defines a sendMessage function that will send a chat message event to the server.

Finally, we can add the code for the ChatScreen component to complete the application. Add the following code to the App.js file:

const ChatScreen = () => {
  const [messages, setMessages] = useState([]);
  const [message, setMessage] = useState('');

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

  const handleSendMessage = () => {
    sendMessage(message);
    setMessage('');
  };

  return (
    <View style={styles.container}>
      <Text>Chat Screen</Text>
      <View>
        {messages.map((msg, index) => (
          <Text key={index}>{msg}</Text>
        ))}
      </View>
      <TextInput
        value={message}
        onChangeText={setMessage}
      />
      <Button
        title="Send"
        onPress={handleSendMessage}
      />
    </View>
  );
};

This code adds the necessary code for the ChatScreen component. It sets up a useEffect hook to listen for incoming messages and adds a TextInput and Button to send messages.

And that's it! You now have a basic chat application built with React Native and Socket.IO.