Build A Chat App With React-native-gifted-chat

Published On March 11th, 2025 Engineering

We’ve all come across React Native Chat Apps. But what’s a Gifted chat app in React Native

In this article, you’ll learn what a React Native Gifted app is, how it stands out from traditional RN apps and how to build one for your business. 

Let’s get started! 

First, 

What is a React Native Gifted Chat?

React Native Gifted Chat is an open-source library. It gives you a complete chat user interface (UI) for building messaging apps in React Native. 

You’ll need to write every line of code yourself to build a regular chat app. Or, at least a minimal coding when you go with a pre-built react native SDK. 

But, Gifted chat takes away that hassle! 

Gifted Chat gives you a set of pre-built, customizable components. All you need to do is plug and play with these components to build the exact app you desire. Consequently,  you complete the app development faster, launch it before your deadline, and give your users a superb chat experience.

Is Gifted Chat only for React Native? Or does it work with other technologies?

Gifted Chat is designed primarily for React Native, which means it works on:

  • iOS and Android: It’s built for mobile apps, ensuring a consistent look and feel across both platforms.
  • Web (with react‑native‑web): With some additional configuration, you can also deploy a web version of your chat app.
Quick-fact:

Why the name “Gifted Chat”? 

The name “Gifted Chat” reflects its goal: to “gift” developers a feature-rich, ready-to-use solution for chat interfaces. Here’s why the name is a really good fit for this library:
1. It comes bundled with many features.
2. Reduces so much work that a developer has to do.
3. Even though it’s pre-built, you can customize the features as much as you want.

Why Should You Go For React Native Gifted Chat? 

Using React Native Gifted Chat can be a smart choice for a good number of reasons:

  1. Gifted Chat speeds up your chat app development with its pre-built components. You can build prototypes and MVPs instantly using the plug and play features. 
  2. You need not worry about elements being pre-built. It will not affect your freedom to customize in any way. Because you can simply override almost every component to make sure the design fits your brand needs. 
  3. You can combine Gifted Chat with any backend services like Firebase service or MirrorFly’s messaging components to create real-time chat capabilities. 
  4. Whether you build it on iOS, Android, or web, the Chat UI will behave the same in all platforms, giving your users a consistent brand experience.

What Are The Common Uses Of React Native Gifted Chat?

Gifted Chat makes building chat apps easier than ever. The library is used for various types of messaging apps. It is primarily used for: 

  • One-on-One Chat/ Direct messaging:
    You can quickly build private conversations between two users.
  • Group Chat:
    For apps that need to handle conversations between multiple users and to efficiently support features like avatars, load earlier messages (pagination), and typing indicators.
  • Prototyping & MVPs:
    Want to quickly test chat features without a huge upfront investment in design or custom coding? Go for Gifted Chat!
  • Real-Time Messaging:
    If you already have a business app and are looking to integrate a custom back-end messaging solution to app messaging capabilities. 

Key Props and How They Work

Alright, before we get into development, let’s explore some of the essential props that React Native Gifted Chat provides:

PropsCharacteristics
messages (array)An array of message objects that get displayed in the chat
text (string)Controls the text in the input field
isTyping (bool)Manages the typing indicator state (default: false)
timeFormat (string) Determines the time format (default: ‘LT’)
dateFormat (string) Sets the date format (default: ‘ll’)
placeholder (string) Text displayed when the input field is empty (default: ‘Type a message…’)
user (object) Contains user information like {_id, name, avatar}
messageIdGenerator (function) Generates unique IDs for new messages (default: UUID v4)
onSend (function)A callback function that’s called when a message is sent. You can use this to update your backend or local state.
loadEarlier (boolean)Enables a button to load earlier messages.
onLoadEarlier (function)A callback that gets triggered when the user taps the “load earlier messages” button.
isLoadingEarlier (boolean)Indicates whether earlier messages are currently being loaded.
renderAvatarCustomize the avatar appearance.
renderBubble  Change how message bubbles look.
renderInputToolbar Replace the default input toolbar with your own component.
renderCustomView Add any additional custom views inside the chat bubble.

MirrorFly Pro Tip

Use a back-end service like Firebase, MirrorFly, or your own server. They take care of logins, saving messages, and real-time updates, so you can easily create a fun and smooth chat app!

Steps To Build A React Native Chat App with Gifted Chat, Firebase, and MirrorFly

In this section, you’ll learn how to set up your React Native project to integrate advanced real‑time messaging features with MirrorFly. Follow along to learn every detail of the code and configuration.

Step1: Prerequisites and Requirements

Before you begin, you’ll have to make sure the following components installed on your development machine:

  • Node.js and npm (or Yarn)
  • React Native CLI
  • Android Studio (for Android-specific integration)
  • Java 7+ (for MirrorFly SDK)
  • Gradle 4.1.0+ (required for Android projects)

MirrorFly Chat SDK for Android Requirements:

  • Android Lollipop 5.0 (API Level 21) or higher
  • targetSdkVersion/compileSdkVersion: 34 or above (for SDK version 7.11.4+ due to Android 14 migration)

Additionally, register for a MirrorFly account to obtain your SDK License Key.

Step 2. Setting Up the React Native Project

Open your terminal and create a new React Native project:

npx react-native init GiftedChatApp

This command initializes a new project called GiftedChatApp. It sets up the required folder structure (including android/, ios/, and a default App.js), enabling you to start coding your application immediately.

Step 3. Installing Dependencies

Navigate to your project directory 

cd /path/to/your/project

Run the following command to install all the necessary packages:

npm install @react-navigation/native 
@react-navigation/stack react-native-gifted-chat
react-native-reanimated react-native-gesture-handler 
react-native-screens react-native-safe-area-context 
@react-native-community/masked-view react-native-vector-icons

The packages you’ll install include libraries for smooth navigation, a friendly chat interface, and enhanced animations. They let you manage app screens easily, handle touch gestures, ensure proper content display on different devices, and even add cool icons to your project.

This is what exactly each package will do:

  • @react-navigation/native: Core library for handling navigation.
  • @react-navigation/stack: Provides stack-based navigation.
  • react-native-gifted-chat: A customizable chat UI component.
  • react-native-reanimated: Enhances animations in your app.
  • react-native-gesture-handler: Improves gesture handling.
  • react-native-screens: Optimizes native screen performance.
  • react-native-safe-area-context: Manages safe area boundaries.
  • @react-native-community/masked-view: Enables masking views.
  • react-native-vector-icons: Offers a wide range of icons for your app.

Step 4. Building Login and Registration Screens

Create two separate screens: one for login and one for registration. These screens use React Native Elements for a polished UI.

4.1. Login Screen

Create a file named LoginScreen.js:

4.1.1. Imports and Setup

// LoginScreen.js

import React, { useState } from 'react';

import { View, StyleSheet } from 'react-native';

import { Input, Button, Text } from 'react-native-elements';

In this first section, we will import all the necessary modules and components. 

We bring in React and the useState hook to allow us to manage state within our functional component. 

The View and StyleSheet components from React Native are used for layout and styling, while the Input, Button, and Text components from the react-native-elements library help build a clean and easy-to-use user interface.

4.1.2. Component Definition and State Variables

const LoginScreen = ({ navigation }) => {

  // State hooks to store user inputs and errors

  const [email, setEmail] = useState('');

  const [password, setPassword] = useState('');

  const [error, setError] = useState(null);

Here, we define the LoginScreen component as a functional component that accepts a navigation prop, which is essential for moving between screens in the app. 

Within the component, we initialize three state variables using useState: one for storing the email, another for the password, and a third for any error messages that might occur during the login process. 

This setup allows the component to reactively update and display user inputs as well as any errors that might happen.

4.1.3. Login Handler Function

// Handler for login button press

  const handleLogin = async () => {

    try {

      // Here you would call Firebase's signInWithEmailAndPassword function

      // await signInWithEmailAndPassword(auth, email, password);

      // On successful login, navigate to the Chat screen.

      navigation.navigate('Chat');

    } catch (err) {

   // Capture and display errors (e.g., invalid credentials)

      setError(err.message);

    }

  };

Next, we will be using the handleLogin function, which is an asynchronous function triggered when the user taps the “Login” button. 

Inside the function, a try-catch block is used to manage the login process. 

In a complete app, you would integrate Firebase’s signInWithEmailAndPassword method to authenticate the user, but in this example, that part is commented out. If the login attempt is successful, the user is directed to the ‘Chat’ screen. Should an error occur (for instance, if the credentials are incorrect), the error is caught and the error message is stored in the error state so it can be displayed to the user.

4.1.4. Building the UI Layout

return (

    <View style={styles.container}>

      <Text h3 style={styles.header}>Login</Text>

      <Input

        placeholder="Email"

        leftIcon={{ type: 'material', name: 'email' }}

        value={email}

        onChangeText={setEmail}

      />

      <Input

        placeholder="Password"

leftIcon={{ type: 'material', name: 'lock' }}

        secureTextEntry

        value={password}

        onChangeText={setPassword}

      />

      {error && <Text style={styles.error}>{error}</Text>}

      <Button title="Login" onPress={handleLogin} />

      <Button

        title="Register"

        type="outline"

        onPress={() => navigation.navigate('Register')}

      />

    </View>

  );

};

The return statement renders a View container that applies the defined styles, ensuring a neat layout with proper spacing. Inside the container, a header labeled “Login” is displayed using the Text component, followed by two input fields: one for the user’s email and another for the password. 

The password field uses the secureTextEntry prop to hide the text for privacy. An error message is conditionally rendered if any error exists, allowing the user to see feedback in case something goes wrong. 

Finally, two buttons are provided: one to trigger the handleLogin function and log the user in, and another to navigate to the registration screen if the user does not yet have an account.

4.1.5. Styling

const styles = StyleSheet.create({

  container: { flex: 1, justifyContent: 'center', padding: 20 },

  header: { marginBottom: 20, textAlign: 'center' },

  error: { color: 'red', textAlign: 'center', marginBottom: 10 }

});

The container style ensures that the view takes up the full screen, centers its children vertically, and has a padding of 20 for proper spacing. 

The header style centers the header text and provides a margin at the bottom to separate it from the rest of the content. 

The error style is applied to any error messages, setting the text color to red, centering it, and adding a margin below for clarity.

4.1.6. Exporting the Component

export default LoginScreen;

Finally we will explore the  LoginScreen component, making it available for use in other parts of the app. 

This allows the login screen to be integrated into the navigation stack and used wherever needed within your project.

4.2. Registration Screen

Create a file named RegisterScreen.js:

4.2.1. Imports and Setup

In this first section, we’ll import all the required modules and components.

// RegisterScreen.js

import React, { useState } from 'react';

import { View, StyleSheet } from 'react-native';

import { Input, Button, Text } from 'react-native-elements';

import { auth } from './firebase'; // Ensure the correct path to your firebase config

We bring in React and the useState hook to build a functional component with state management. 

The View and StyleSheet components from React Native help us create and style the layout, while the Input, Button, and Text components from react-native-elements provide a user-friendly interface. Additionally, we import the auth object from our Firebase configuration, which is used to handle user authentication.

4.2.2. Component Definition and State Variables

Next, let us define the RegisterScreen component as a functional component that accepts a navigation prop, which allows us to move between screens in the app.

const RegisterScreen = ({ navigation }) => {

  const [email, setEmail] = useState('');

  const [password, setPassword] = useState('');

  const [error, setError] = useState(null);

Here, we set up three state variables using useState: one to store the user’s email, another to store the password, and a third for any error messages that might occur during the registration process. 

This setup enables the component to dynamically update based on user input and to display any error feedback.

4.2.3. Register Handler Function

This section defines the handleRegister function, which is called when the user taps the “Register” button. 

// Handler for registration button press

  const handleRegister = async () => {

    try {

      // Create a new user using Firebase authentication

      await auth.createUserWithEmailAndPassword(email, password);

      navigation.navigate('Chat');

    } catch (err) {

      setError(err.message);

    }

  };

The function is asynchronous because it interacts with Firebase’s authentication service. Inside the try-catch block, the code attempts to create a new user account using the provided email and password with Firebase’s createUserWithEmailAndPassword method. 

If the registration is successful, the user is navigated to the ‘Chat’ screen. If an error occurs during the process such as an invalid email format or a weak password the error is caught and its message is stored in the error state to be displayed on the screen.

4.2.4. Building the UI Layout

Next up, let’s construct the user interface for the registration screen. 

return (

    <View style={styles.container}>

      <Text h3 style={styles.header}>Register</Text>

      <Input

        placeholder="Email"

        leftIcon={{ type: 'material', name: 'email' }}

        value={email}

        onChangeText={setEmail}

      />

      <Input

        placeholder="Password"

        leftIcon={{ type: 'material', name: 'lock' }}

        secureTextEntry

        value={password}

        onChangeText={setPassword}

      />

      {error && <Text style={styles.error}>{error}</Text>}

      <Button title="Register" onPress={handleRegister} />

    </View>

  );

};

The return statement renders a View container that uses the defined styles for layout. Inside the container, a header labeled “Register” is displayed using the Text component, giving users a clear indication of the screen’s purpose. 

Two Input components are used to capture the user’s email and password, with each field featuring an appropriate icon. The password input has the secureTextEntry prop enabled so that the characters are hidden for security. 

If there is any error during registration, an error message is conditionally rendered on the screen. Finally, a “Register” button is provided to trigger the handleRegister function when pressed.

4.2.5. Styling

Once we set up the UI layout, we will start defining the styles using React Native’s StyleSheet

const styles = StyleSheet.create({

  container: { flex: 1, justifyContent: 'center', padding: 20 },

  header: { marginBottom: 20, textAlign: 'center' },

  error: { color: 'red', textAlign: 'center', marginBottom: 10 }

});

The container style makes sure the view takes up the full available space, centers its children vertically, and provides adequate padding. 

The header style centers the header text and adds some margin below it for clear separation from other elements. 

The error style is applied to any error messages, setting the text color to red and centering it, along with a margin to ensure it doesn’t clutter the layout.

4.2.6. Exporting the Component

export default RegisterScreen;

As we did in 4.2.6, we’ll finally export the RegisterScreen component, making it accessible for use in other parts of the application, such as integrating it into your app’s navigation stack.

Step 5. Setting Up Firebase for User Authentication

Create a configuration file named firebase.js:

5.1. Importing Firebase Modules

In this first step, we import the core Firebase module using firebase/app which provides the main Firebase functionality. Then, we import firebase/auth to include Firebase’s authentication features, enabling our app to perform tasks like signing in and signing up users. This is how we’ll do it:

import firebase from 'firebase/app';

import 'firebase/auth';

5.2. Creating the Firebase Configuration Object

Next, we’ll define a configuration object named firebaseConfig that holds the details required to connect our app to the correct Firebase project.

// Your Firebase configuration object (replace with your actual configuration)

const firebaseConfig = {

  apiKey: 'YOUR_API_KEY',

  authDomain: 'your-app.firebaseapp.com',

  projectId: 'your-app-id',

  storageBucket: 'your-app.appspot.com',

  messagingSenderId: 'YOUR_SENDER_ID',

  appId: 'YOUR_APP_ID',

};

This object contains keys like apiKey, authDomain, and appId, among others. These values should be replaced with the actual configuration details from your Firebase console.

5.3. Initializing Firebase

In this segment, let’s check whether Firebase has already been initialized using if (!firebase.apps.length).

// Initialize Firebase if not already initialized

if (!firebase.apps.length) {

  firebase.initializeApp(firebaseConfig);

}

If no Firebase app exists, it calls firebase.initializeApp(firebaseConfig) to initialize Firebase with our configuration object. This prevents multiple initializations if the module is imported in different parts of the application.

5.4. Exporting Firebase Services

export const auth = firebase.auth();

export default firebase;

Finally, we’ll export the Firebase authentication service as auth so that it can be easily imported and used in other files for authentication-related tasks. Additionally, we export the default Firebase instance, allowing access to other Firebase services if needed elsewhere in your project.

Step 6. Building the Chat Screen with react-native-gifted-chat

Create a file named ChatScreen.js:

6.1. Importing Modules

import React, { useState, useCallback, useEffect } from 'react';
import { GiftedChat } from 'react-native-gifted-chat';
import { View, StyleSheet } from 'react-native';

During import, we bring in React along with hooks like useState, useCallback, and useEffect to manage state and lifecycle events within our component. 

The GiftedChat component is imported from the react-native-gifted-chat library to handle the chat UI, and basic layout components such as View and StyleSheet are brought in from React Native.

6.2. Defining the ChatScreen Component and State Initialization

Next, it’s time to define the ChatScreen functional component.

const ChatScreen = () => {

  const [messages, setMessages] = useState([]);

Inside the component, we use the useState hook to initialize a state variable called messages with an empty array. This state will store all the chat messages and be updated as new messages are sent or loaded.

6.3. Loading Initial Messages with useEffect

This segment uses the useEffect hook to load an initial message when the component mounts.

// Populate with an initial message (in production, load history from a backend)

  useEffect(() => {

    setMessages([

      {

        _id: 1,

        text: 'Hello developer!',

        createdAt: new Date(),

        user: {

          _id: 2,

          name: 'MirrorFly Bot',

          avatar: 'https://placeimg.com/140/140/any',

        },

      },

    ]);

  }, []);

In the example here, a welcome message from a “MirrorFly Bot” is set up, but in a real-world app, you would load the chat history from a backend service. 

The empty dependency array ([]) ensures that this effect runs only once when the component is first rendered.

6.4. Handling New Messages with onSend

// Append new messages to the chat  
const onSend = useCallback((newMessages = []) => {    
setMessages((previousMessages) =>      
GiftedChat.append(previousMessages, newMessages)    
);   
 // In a full app, send the message to the backend 
(MirrorFly) here. 
 }, []);

The onSend function is created using useCallback to efficiently handle new messages. When a user sends a message, this function appends it to the existing list of messages using the GiftedChat.append helper function. 

Carrying out this step ensures that the newest messages appear at the top. The comment notes that in a complete app, you would also send the new message to your backend (such as MirrorFly) for persistence and real-time updates.

6.5. Rendering the Chat Interface

return (

    <View style={styles.container}>

      <GiftedChat

        messages={messages}

        onSend={onSend}

        user={{ _id: 1 }} // The current user's ID

      />

    </View>

  );

};

Next, in the return statement, the chat interface is rendered inside a View component. The GiftedChat component takes in the current list of messages, the onSend function to handle new messages, and a user object with a unique ID representing the current user. 

This setup renders a fully functional chat UI where users can see messages and send new ones.

Step 7. Integrating MirrorFly Chat SDK for Android

This section explains how to integrate MirrorFly into your Android project so that your React Native app (specifically the Android module) can handle real‑time messaging.

7.1. Configure the Android Project

Step 1: Open or Create Your Android Project

  • Use Android Studio to create a new project or open your existing React Native project’s android/ folder.

Step 2: Configure Gradle Repositories

For Gradle 6.8 or higher, add the following to your settings.gradle:

dependencyResolutionManagement {

    repositories {

        mavenCentral()

        google()

        jcenter()

        maven {

            url "https://repo.mirrorfly.com/release"

        }

    }

}

This code configures dependency resolution in your Gradle build by specifying a set of repositories where Gradle should search for libraries and dependencies. It lists popular repositories like Maven Central, Google, and JCenter, ensuring that standard dependencies are easily found. 

Additionally, it includes a custom Maven repository at “https://repo.mirrorfly.com/release,” which likely hosts specific artifacts or libraries provided by MirrorFly. This setup ensures that your project can fetch both common and custom dependencies needed during the build process.For Gradle 6.7 or lower, add the corresponding configuration in your root build.gradle.

Step 3: Add MirrorFly Dependency

In your app/build.gradle file, add:

dependencies {   
implementation 
'com.mirrorfly.sdk:mirrorflysdk:7.13.13
'}

Step 4: Resolve Library Conflicts

In your gradle.properties file, add:

android.enableJetifier=true

Step 5: Update AndroidManifest.xml

Ensure you have the necessary permissions by adding the following line:

<uses-permission 

android:name="android.permission.INTERNET" />

7.2. Initialize the MirrorFly Chat SDK

Create or update your Application class (e.g., MyApplication.java) to initialize the MirrorFly SDK.

MyApplication.java

// MyApplication.java

package com.example.giftedchatapp;

import android.app.Application;

import android.util.Log;

import com.mirrorfly.sdk.ChatManager;

public class MyApplication extends Application {

    @Override

    public void onCreate() {

        super.onCreate();

        // Initialize MirrorFly with your License Key

        ChatManager.initializeSDK("YOUR_LICENSE_KEY", (isSuccess, throwable, data) -> {

            if(isSuccess){

                Log.d("TAG", "initializeSDK success");

            } else {

                Log.d("TAG", "initializeSDK failed with reason " + data.get("message"));

            }

        });

    }

}

This code defines a custom Application class for your Android app. When the app starts, the onCreate method is called, and it initializes the MirrorFly ChatManager SDK using your license key. 

The initialization process uses a callback to determine whether it was successful. If it is, a success message is logged; if not, an error message along with the failure reason is logged. This ensures that the MirrorFly SDK is ready to handle chat functionalities as soon as your app launches.Application Class Registration:
Update your AndroidManifest.xml to register your Application class:

<application

    android:name=".MyApplication"

    android:icon="@mipmap/ic_launcher"

    android:label="@string/app_name"

    android:theme="@style/AppTheme">

    <!-- Other activities -->

</application>

This XML snippet is part of your AndroidManifest.xml file and defines the overall application settings. The android:name=”.MyApplication” attribute tells the system to use your custom MyApplication class as the application instance, which allows you to perform global initialization tasks, like initializing the MirrorFly SDK, when the app starts. 

Additionally, the snippet specifies the app’s icon, label, and theme, ensuring that these resources are applied throughout your app, while also leaving room for other activities to be defined within the application block.

7.3. Register a User with MirrorFly

After initialization, register your user. This should be done once per session.

// In an appropriate activity or service after login:

FlyCore.registerUser("USER_IDENTIFIER", (isSuccess, throwable, data) -> {

    if (isSuccess) {

        Boolean isNewUser = (Boolean) data.get("is_new_user"); // Check if user is new

        String userJid = (String) data.get("userJid"); // Example: 12345678@xmpp-preprod-sandbox.mirrorfly.com

        JSONObject responseObject = (JSONObject) data.get("data");

        String username = responseObject.getString("username");

        // Continue with app flow after successful registration.

    } else {

        // Handle registration error (log throwable for details)

    }

});

The registerUser method is called with a unique user identifier (which should be replaced with an actual ID) and a callback function that processes the result. 

In the callback, if registration is successful (indicated by isSuccess being true), the code retrieves several pieces of information from the data object: it checks if the user is new via the is_new_user flag, extracts the user’s JID (a unique identifier used in the chat system), and retrieves a JSON object containing additional details such as the username. 

If the registration fails, the error details can be handled using the provided throwable object. This approach allows your app to seamlessly integrate user registration into the flow after login, ensuring that all necessary user details are available for further use in the application.

7.4. Establish a Connection and Listen for Events

MirrorFly automatically attempts to connect to the Chat Server after registration. To monitor connection status, set up a connection listener.

ChatManager.setConnectionListener(new ChatConnectionListener() {
    @Override
    public void onConnected() {
        // Connection established: proceed to load user profile or chat UI.
    }

    @Override
    public void onDisconnected() {
        // Handle disconnection events.
    }

    @Override
    public void onConnectionFailed(@NonNull FlyException e) {
        // Log or display connection failure details.
    }

    @Override
    public void onReconnecting() {
        // Inform user that the app is attempting to reconnect.
    }
});

This code sets up a connection listener for your chat system using the ChatManager. It attaches a new ChatConnectionListener that overrides four methods to handle various connection events. 

When the connection is successfully established, the onConnected method is triggered, allowing you to load the user’s profile or chat interface. If the connection is lost, onDisconnected is called to manage disconnection events. 

If there are any issues while establishing a connection, onConnectionFailed is invoked, providing details of the failure for logging or display purposes. 

Additionally, onReconnecting informs you when the app is attempting to re-establish the connection. Overall, this listener ensures that your app can effectively respond to changes in the chat connection status.

7.5. Generate User JID

To generate a Jabber ID (JID) for any user, call:

String userJid = FlyUtils.getJid(“USER_NAME”);

7.6. Sending a One-to-One Message

To send a message to another user, create a TextMessage object and call the send function.

TextMessage textMessage = new TextMessage();

textMessage.setToId("RECIPIENT_JID");  // The recipient’s JID

textMessage.setMessageText("Hello, how are you?");  // Your message text

FlyMessenger.sendTextMessage(textMessage, (isSuccess, error, chatMessage) -> {

    if (isSuccess) {

        // Message sent successfully; update UI or log response.

    } else {

        // Handle error in message sending.

    }

});

This code snippet demonstrates how to create and send a text message using the FlyMessenger service. First, a new TextMessage object is created and configured by setting the recipient’s JID and the message content (“Hello, how are you?”). 

Then, the FlyMessenger.sendTextMessage method is called with the text message and a callback function. 

The callback checks if the message was sent successfully, allowing you to update the user interface or log the response accordingly, or handle any errors that may have occurred during the sending process.

7.7. Receiving Messages

Set up a listener to capture incoming messages.

ChatEventsManager.setupMessageEventListener(new MessageEventsListener() {

    @Override

    public void onMessageReceived(@NonNull ChatMessage message) {

        // Handle the incoming message (update chat UI accordingly).

    }

});

This code registers a message event listener using the ChatEventsManager. By passing a new MessageEventsListener with an overridden onMessageReceived method, the application is set up to automatically handle incoming chat messages. Whenever a new message arrives, the onMessageReceived method is triggered, allowing you to update the chat UI or perform other actions in real time.

Step 8. Integrating with React Native

While the native Android integration (steps in Section 7) handles real‑time messaging with MirrorFly, you can bridge these native functionalities to your React Native code using Native Modules or libraries like react-native-bridge. This allows your JavaScript code (which drives Gifted Chat) to call native functions like sending and receiving messages.

For example, you might expose a native module that provides methods such as sendMessage or initializeMirrorFly that can be invoked from your React Native components. Detailed bridging steps are available in the React Native documentation.

Final Thoughts and Next Steps

Using React Native Gifted Chat with the MirrorFly Chat SDK gives you a complete and flexible solution for building a chat app that not only looks great but also performs exceptionally well. 

Gifted Chat handles the front-end by providing ready-made, customizable elements like message bubbles, avatars, and input fields that work seamlessly on iOS, Android, and the web. 

On the back end, MirrorFly Chat SDK adds powerful messaging features: supporting instant messaging, voice, and video calls while keeping your app secure and running smoothly. 

What really makes MirrorFly stand out is its total customizability. You can add, modify or remove any feature and workflow to your exact needs, and you even own your data and source code. 

It offers options for hiring a dedicated team, flexible hosting, and a white-label solution that lets you fully brand your chat experience. 

Want to know more about this solution? Contact MirrorFly Team today! 

Rajeshwari

Rajeshwari is a skilled digital marketer, passionate about SEO and exploring the latest trends and tech innovations in communication and Chat APIs. With a keen eye for detail, she helps brands improve their online visibility, and she is always eager to stay ahead in the evolving digital landscape.

Leave a Reply

Your email address will not be published. Required fields are marked *

GET A DEMO
Request Demo