Documentation
React SDK

Introduction

In today's fast-paced digital environment, real-time communication is essential for both personal and professional interactions. For developers, integrating reliable, seamless chat functionality into applications is critical. Commt offers a comprehensive solution with pre-built, customizable UI components, enabling you to integrate real-time messaging into your app quickly and efficiently.

Whether you're building a ReactJS or React Native app, Commt provides an intuitive, feature-rich chat interface, helping you deliver a robust user experience with minimal setup. This document will guide you through the process of implementing Commt in your application, streamlining communication and enhancing user engagement.


Installation

Go to the root directory of your project and run one of these commands in your terminal.

npm i -S @commt/react-sdk

or

yarn add @commt/react-sdk

Resources


Wrapper

As an initial step, encapsulate your application within the CommtProvider. This step is crucial for integrating your application with the capabilities provided by the Commt plugin. The CommtProvider sets up a context and provides certain functionalities to be used within your App. This integration enables your application to seamlessly communicate with and benefit from the Commt plugin.

import CommtProvider from "@commt/react-sdk";
 
const App = () => {
  return (
    {/* All your route configurations etc. */}
  );
};
 
const WrappedComponent = CommtProvider(App);
export default WrappedComponent;

or

import CommtProvider from "@commt/react-sdk";
 
const App = () => {
  return (
    <CommtProvider>
      {/* All your route configurations etc. */}
    </CommtProvider>
  );
};
 
export default App;

Hooks

To ensure smooth transfer of client information to the package, it is essential to integrate hooks into your application prior to utilizing the UI components. By incorporating these hooks into your codebase, you can establish a connection between the client information and the package, allowing for seamless data transfer. This integration step is crucial for the proper functioning of the UI components and ensuring that your application effectively utilizes the available resources.

useInitiate

This hook adds the necessary configurations to the Commt package and verifies client information.

Usage:

import CommtProvider from "@commt/react-sdk";
import { useInitiate } from "@commt/react-sdk/hooks";
 
const ClientConfig = {
  apiKey: "123456789?",
  projectId: "0987654321?",
  secretKey: "123456789018A_7JzPo?23F+4y#erPL"
};
 
const App = CommtProvider(() => {
  useInitiate(ClientConfig); // Initiate a client
 
  return (
    {/* All your route configurations etc. */}
  );
});

Client Props (required parameter) Type Definition:

interface ClientProps {
  apiKey: 'string'
  subscriptionKey: 'string',
  secretKey: 'string'
}
{
  apiKey: '123456789?'
  subscriptionKey: '0987654321?',
  secretKey: 'j?&lt;ljAmS&lt;e'
}

Note: The secret key to be used here is the key required to encrypt your messages with the "AES" algorithm. SecretKey length must be 16, 24, 32.

useSetSelfUser

To ensure that the Commt package is aware of the active user logged into your application, it must to be defined for the active user information using the useSetSelfUser hook.

Usage:

import { useSetSelfUser } from "@commt/react-sdk/hooks";
 
const Login = () => {
  const setSelfUser = useSetSelfUser();
 
  useEffect(
    if (activeUser) {
      setSelfUser(activeUser);
    }
  }, [activeUser]);
 
  return (...);
}

Props Definition:

activeUser: Logged user in app, required, for expected user type

useSetUsers

The useSetUsers hook is designed to manage and update the user list in the plugin's state for rendering purposes within pre-built components. It utilizes the provided user list along with specific user properties defined in UserProps. Additionally, it fetches and updates user online status/indicator from Commt services by using chatAuthId field of user.

Usage:

import { useSetUsers } from "@commt/react-sdk/hooks";
 
const Home = () => {
  const setUsers = useSetUsers();
 
  useEffect(async () => {
    if (users.length > 0) {
      await setUsers(users);
    }
  }, [users]);
 
  return (...);
}

Props Definition:

The useSetUsers hook doesn't take any explicit parameters. However, it relies on the users array, where each element conforms to the UserProps structure, containing user details required for rendering and identification.

useSetRooms

The useSetRooms hook is designed to manage and update the room list in the plugin's state for rendering purposes within pre-built components. It utilizes the provided room list along with specific room properties defined in RoomProps. Additionally, it fetches and updates rooms last-message-read-token from Commt services by using chatRoomAuthId field of rooms. This ensures that the message read indicator works properly.

Usage:

import { useSetRooms } from "@commt/react-sdk/hooks";
 
const Home = () => {
  const setRooms = useSetRooms();
 
  useEffect(async () => {
    if (rooms.length > 0) {
      await setRooms(rooms);
    }
  }, [rooms]);
 
  return (...);
}

Props Definition:

The useSetRooms hook doesn't take any explicit parameters. However, it relies on the rooms array, where each element conforms to the RoomProps structure, containing room details required for rendering and identification.

useSetMessages

The useSetMessages hook is designed to manage and update the message list in the plugin's state for rendering purposes within pre-built components. It utilizes the provided message list along with specific message properties defined in MessageProps. It also configures messages by rooms.

Usage:

import { useSetMessages } from "@commt/react-sdk/hooks";
 
const Home = () => {
  const setMessages = useSetMessages();
 
  useEffect(
    if (messages.length > 0) {
      setMessages(messages);
    }
  }, [messages]);
 
  return (...);
}

Props Definition:

The setMessages function requires a message list as a parameter. It's crucial that each element in this list follows the structure outlined in MessageProps which contains detailed information for each message. Adhering to the MessageProps structure ensures that the messaging system functions as expected, providing a clear and organized representation of each message in the pre-built components.

Note: It is recommended to limit the message array to 10 messages per room when uploading the first set of messages.

useGetActiveRoom

The useGetActiveRoom hook is designed to to retrieve information about the currently selected active room within a Commt package. It returns two important pieces of information:

  • roomId: contains the ID of the currently active room. If there is no active room, this value will be undefined.

  • participants: If an active room already exists, the participants value is undefined. However, if the goal is to create a new room, it comprises an array containing the participant IDs for the new room.

Usage:

import { useGetActiveRoom } from "@commt/react-sdk/hooks";
 
const Chats = () => {
  const { roomId, participants } = useGetActiveRoom();
 
  return (...);
};

Components

Messages Header

The message header is a user interface (UI) component that you can use on any screen within your application. It serves as a header and is labeled with the title 'Messages'.

Appearance

message-header

Usage

import { MessagesHeader } from "@commt/react-sdk/components";
 
const Chats = () => {
  return (
    <div>
      <MessagesHeader popUpButtons={customButtons} />
    </div>
  );
};

Props Definition

Message Header utilizes the popUpButtons property, providing a mechanism for developers to define a personalized set of buttons. This customization empowers developers to tailor the buttons within the Message Header according to their specific requirements.

popUpButtons

popUpButtons:

Not required prop. Array of ButtonItem object.

Interface Definition

interface ButtonItem {
  icon?: 'React.JSX.Element'
  title: 'string',
  onPress: '() => void' ,
}

Example Custom Buttons

const customButtons = [
  {
    icon: <CustomIcon />,
    title: "Extension",
    onPress: () => {
      console.log(" Extension Press");
    },
  },
]

Search Input

The SearchInput component is a user interface (UI) element specifically created for searching within the Message List. It is meant to be used together with the Message List component to provide a seamless search experience for users. By incorporating the SearchInput component into your application, users can easily search for specific messages within the Message List, improving the overall usability and functionality of your messaging system.

Appearance

search-input

Usage

import { SearchInput } from "@commt/react-sdk/components";
 
const Chats = () => {
  return (
    <div>
      <SearchInput />
    </div>
  );
};

Message List

The Message List component is a UI component that displays a list of messaging rooms and their last messages. It serves as a convenient way for users to access and switch between different conversations within your application. When a user clicks on a specific room, the selectedRoom (global state) in the @commt/react-sdk package will be updated according to the clicked room, and when the selectedRoom information is updated, the chat components will display the details of the clicked room.

Appearance

message-list-react

Usage

import { MessageList } from "@commt/react-sdk/components";
 
const Chats = () => {
  return (
    <div>
      <MessageList/>
    </div>
  );
}

Room Card

The Room Card component is a UI element crafted using the room properties specified in RoomProps for a particular room. It presents the text of the room's last message, read and time information, and also indicates the number of unread messages from the opposite user. In one-to-one messaging, it displays the avatar, name, online status, and writing status of the opposite user. For group rooms, it shows the group avatar, name and the names of users who are currently writing, along with their writing status.

Appearance

room-card-react

Usage

import { RoomCard } from "@commt/react-sdk/components";
 
const Chats = () => {
  return (
    <div>
      <RoomCard room={roomItem} />
    </div>
  );
};

Props Definition

The room card component receives a prop called room. By passing the room prop, the room card component obtains the necessary data to display information about the room.

room: This is an object that has the properties specified in RoomProps.


Chat Header

The chat header is an essential UI component that provides important information about the chat participants. In one-to-one messaging rooms, it shows the avatar of the opposite user, their online status, writing status, and name. For group messaging rooms, it displays the group avatar, group name, and the names of the group members. This allows users to quickly identify who they are chatting with and provides a visual representation of the participants. In addition, when the information about the selectedRoom (global state) in the @commt/react-sdk package is updated, the chat header component interface will dynamically update based on the selected room's information.

Appearance

chat-header-react

Usage

import { ChatHeader } from "@commt/react-sdk/components";
 
const Chats = () => {
  return (
    <div>
      <ChatHeader 
        popUpButtons={customButtons} 
        onUserProfileClick={YOUR_CALLBACK_FUNCTION}
      />
    </div>
  );
};

Props Definition

The chat header component receives two props: popUpButtons and onUserProfileClick. The popUpButtons prop allowing developers to define and utilize custom buttons along with their respective functions.

  • onUserProfileClick (not required): defines a callback function that is invoked when the user clicks on the avatar or username in header. It provides a way to offer additional functionality or navigation options when the user engages with the user profile elements.

  • popUpButtons (not required): The popUpButtons prop of the Message Header component and the popUpButtons prop of the Chat Header component have the same properties. These properties define the buttons that are displayed in the header's popup menu.

PopUpButtons Example Definition

const customButtons = [
  {
    icon: <MDBIcon fas icon="smile" />,
    title: "Document",
    onPress: () => {
      console.log(" Document Press");
    },
  },
  {
    title: "Bookmarks",
    onPress: () => {
      alert(" Bookmarks Press");
    },
  },
];

PopUpButtons Appearance

popup-buttons

Chat

The chat component is a UI component that displays message bubbles based on the messaging information of the selectedRoom (global state) in the @commt/react-sdk package.

Appearance

chat-react

Usage

import { Chat } from "@commt/react-sdk/components";
 
const Chats = () => {
  return (
    <div>
      <Chat loadMoreMessages={loadMoreMessages} />
    </div>
  );
};

Props Definition

The chat component uses a prop called loadMoreMessages, which helps load previous messages in the chat screen in a specific order.

loadMoreMessages: The loadMoreMessages prop is a feature used to fetch previous messages from the database when the user scrolls the chat screen. To implement this functionality, you need to create a function that takes the roomId, skip, and limit values as parameters. This function will then retrieve the messages belonging to that room based on the provided limit value.

Function Parameter:

  • roomId (required): A string representing the ID of the chat room.
  • skip (required): A number representing the number of messages to skip.
  • limit (required): A number representing the maximum number of messages to retrieve.

Function Return Parameter:

  • messages (required): This represents the list of messages that are fetched from the server. The type of this list should be an array of Message Props.
  • hasNext (not required): A boolean indicating whether there are more messages to load.

Message Input

The message input component is a UI element that consists of an input bar, an emoji icon, and a send icon. It allows users to write messages, add emojis, and send messages.

Appearance

message-input

Usage

import { MessageInput } from "@commt/react-sdk/components";
 
const Chats = () => {
  return (
    <div>
      <MessageInput/>
    </div>
  );
}

Data Types

User Data Type

Generic user props:

Prop nameRequiredTypeDescription
_idYesStringUser Id
chatAuthIdYesStringUser's chat auth Id (required to match user in Commt system)
usernameYesStringUser name (will be display in the components)
avatarYesStringUser avatar uri/source (will be display in the components)

Note: The 'id' and 'chatAuthId' properties must be prefixed with the keyword 'system' when defining them for system users. This naming convention helps to clearly distinguish system users from regular users and ensures consistency in the codebase.


Room Data Type

Generic room props:

Prop nameRequiredTypeDescription
participantsYesString[_id]User Ids in the particular room
roomIdYesStringUnique room id field
chatRoomAuthIdYesStringRoom's chat auth Id (required to match room in Commt system)
groupNameNoStringIf the room is a community room the name of the group/community
groupAvatarNoStringIf the room is a community room the avatar of the group/community

Note: For system users, the "system_" prefix must to be added to the beginning of the ID when defining room participant IDs.


Message Data Type

Generic message props:

Prop nameRequiredTypeDescription
_idYesStringMessage Id
textYesStringMessage content
createdAtYesDateMessage sent time
typeYesStringMessage type such as "text" | "button" | "image" (default text)
roomIdYesStringRoom id where the message was sent
userYesStringMessage sender id
systemNoBooleanWhether the message is a system message or not (default false)
imageNoStringImage uri for system messages, if the system message is true and type field is image, system message will rendered image.
onPressNovoidPress action for button system message, if the system message is true and type field is button then the button will be rendered with text and onPress action.


Playground

How to Use the @commt/react-sdk to Create a Chat Web Application in React

Example web application: commt-react-playground

commt-react-playground

In this article, we will explore how to utilize the @commt/react-sdk package to develop a chat web application in React. The @commt/react-sdk package provides a messaging list and messaging interface, making it ideal for building chat functionality into your web app. We will walk through the installation process, as well as the various hooks and components provided by the package. By the end of this guide, you will have a solid understanding of how to integrate the @commt/react-sdk package into your own application.

Installation

To begin, let's install the @commt/react-sdk package into our application. You can add it by following the installation step.

Once the package is installed, we can move on to utilizing its various hooks and components.

Wrapper and Initiate Hook

Before using the @commt/react-sdk components we must wrap our application with the provider of the package. In the App component, use the useInitiate hook of @commt/react-sdk to set client information and configurations.

import CommtProvider from "@commt/react-sdk";
import { useInitiate } from "@commt/react-sdk/hooks";
 
const ClientConfig = {
  apiKey: "123456789?",
  projectId: "0987654321?",
  secretKey: "123456789018A_7JzPo?23F+4y#erPL"
};
 
function App() {
  const client = useInitiate(ClientConfig);
 
  return (
    {/* All your route configurations etc. */}
  );
};
 
const WrappedComponent = CommtProvider(App);
 
export default WrappedComponent;

App (commt-react-playground) Hooks

There are four hooks in the sample application. These hooks are created using React Query (opens in a new tab) and serve the purpose of fetching data from the database or saving it. Let's take a look at the available hooks:

  • useGetRooms: This hook retrieves the list of chat rooms from the database.
  • useGetMessages: This hook retrieves the messages from the database.
  • useGetUsers: This hook retrieves the list of users from the database.
  • useSaveUser: This hook is responsible for saving the active user's information to the database.

Application Pages

Our sample application consists of three: Login, Home, Chats. Each page serves a specific purpose and utilizes the @commt/react-sdk package to provide a customized user interface for chat functionality.

Login Page

On the Login page, users enter their credentials and log in to the application. Once the user's information is validated, we can save it to the database using the useSaveUser hook. This hook also ensures that by passing the user's data to the useSetSelfUser hook of @commt/react-sdk, we are notifying the package about the active user.

Detail of the app's useSaveUser hook:

import { useSetSelfUser } from "@commt/react-sdk/hooks";
{...}
 
export default function useSaveUser() {
  {...}
 
  const queryClient = useQueryClient();
  return useMutation({
    mutationFn: saveUser,
    onSuccess: (user) => {
      {...}
      //pass active user to package
      setSelfUser(user);
    },
  });
}

Home Page

The Home page fetches the necessary data using the useGetRooms, useGetMessages and useGetUsers app hooks. These hooks retrieve the chat rooms, messages and user information from the database respectively. Once the data is fetched, we can set it using the useSetRooms, useSetUsers and useSetMessages hooks provided by the @commt/react-sdk package. It is important to note that the data transmitted to the commt hooks must match MessageProps, RoomProps and UserProps. If the data does not align, we need to format it accordingly before setting it.

import { 
  useSetUsers,
  useSetRooms,
  useSetMessages
} from "@commt/react-sdk/hooks"
{...}
 
const Home = () => {
  {...}
 
  // get our data from backend service using app's hook
  const { data: users, isSuccess: isUsersSuccess } = useGetUsers();
  const { data: rooms, isSuccess: isRoomsSuccess } = useGetRooms();
  const { data: messages, isSuccess: isMessagesSuccess } = useGetMessages();
 
  // @commt/react-sdk hooks
  const setUsers = useSetUsers();
  const setRooms = useSetRooms();
  const setMessages = useSetMessages();
 
  async function setContextData() {
 
    // Format data in accordance with @commt/react-sdk data structure
    const formattedMessages = messages?.map((message: MessageProps) => ({
      _id: message._id,
      text: message.message,
      createdAt: message.createdAt,
      type: message.type,
      roomId: message.roomId,
      user: message.senderId,
    }));
 
    const formattedRooms = rooms?.map((room: RoomProps) => {
      return {
        participants: room.participants,
        roomId: room.roomId,
        // Match between Commt db and yours
        chatRoomAuthId: room.chatRoomAuthId, 
        unReadMessageCount: 0,
        ...(room.communityName && { groupName: room.communityName }),
        ...(room.communityAvatar && { groupAvatar: room.communityAvatar }),
      };
    });
    // Pass the received data from the app's hooks to the package
    await setUsers(users);
    await setRooms(formattedRooms);
    setMessages(formattedMessages);
  }
 
  useEffect(() => {
    if (isUsersSuccess && isRoomsSuccess && isMessagesSuccess) {
      setContextData();
    }
  }, [isUsersSuccess, isRoomsSuccess, isMessagesSuccess])
  
  return({...})
};

Chats Page

On the Chats page, we use the MessagesHeader, SearchInput, MessageList, ChatHeader, Chat and MessageInput UI components from the @commt/react-sdk package. These components are customized based on the messages, rooms, and users information provided on the home page, resulting in a user-friendly interface for our sample application.

On the Chats page, we utilize the useGetActiveRoom hook from the @commt/react-sdk package. This hook retrieves the id of the currently selected room; if no room is selected, it provides participant information for a new room to be created. If no room is selected and we choose not to create a room, we only render the MessageHeader, SearchInput, and MessageList components. If a room is selected, the ChatHeader, Chat, and MessageInput components necessary for messaging are rendered on the Chats page.

import {
  MessagesHeader,
  SearchInput,
  MessageList,
  ChatHeader,
  Chat,
  MessageInput,
} from "@commt/react-sdk/components";
import { useGetActiveRoom } from "@commt/react-sdk/hooks";
{...}
 
const Chats = () => {
  const { roomId, participants } = useGetActiveRoom();
 
  return (
    {...}
      <MDBCol
        md={roomId || participants ? "6" : "12"}
        lg={roomId || participants ? "5" : "12"}
        className="mb-4 mb-md-0"
      >
        <div className="p-3">
          <MessagesHeader popUpButtons={customButtons} />
          <SearchInput />
          <MessageList />
        </div>
      </MDBCol>
      {(roomId || participants) && (
        <MDBCol md="6" lg="7">
          <ChatHeader popUpButtons={customButtons} />
          <Chat loadMoreMessages={loadMoreMessages} />
          <MessageInput />
        </MDBCol>
      )}
    {...}
  );
};
 
export default Chats;

Additionally, we can customize the MessagesHeader or ChatHeader components by adding a custom button to enhance the user experience. An example of a custom button is shown below.

const customButtons = [
  {
    icon: <MDBIcon fas icon="smile" />,
    title: "Extensions",
    onPress: () => {
      console.log(" Extensions Press");
    },
  },
]

loadMoreMessages Function in Our App

The loadMoreMessages function in our example application is defined in the service folder. This function is responsible for retrieving additional messages from the database for a given chat room, subject to a certain limit. Any message object returned by this function must conform to the structure defined by the MessageProps type. If your messages do not conform to this structure, you will need to format them accordingly. We also use the hasNext property to indicate whether there are more messages in the database that belong to the specified room to make request.

{...}
export const loadMoreMessages = async (props) => {
  const { roomId, skip, limit } = props;
 
  try {
    const response = await axios.get(chat, {
      params: {
        roomId,
        skip,
        limit,
      },
    });
 
    const formattedMessages = response.data.messages?.map(
      (message: MessageProps) => ({
        id: message._id,
        text: message.message,
        createdAt: message.createdAt,
        type: message.type,
        roomId: message.roomId,
        user: message.senderId,
      }),
    );
 
    return { messages: formattedMessages, hasNext: response.data.hasNext };
  } 
  {...}
};

Conclusion

In this article, we have explored how to use the @commt/react-sdk package by creating a chat web application in React. We covered the installation process, available hooks and the pages that make up our sample web application. By following the steps outlined in this guide, you can easily integrate the @commt/react-sdk package into your own web application and customize it to meet your specific requirements. Happy coding!


© 2025 Commt. All rights reserved.
Welcome to Commt, I am here to guide you!
Chat with Commt AI Bot
commt-chatbot-ai-avatar

Hi, welcome!

I am Commt's AI user, which is a future feature that developers work on, to provide for the clients to re-train and integrate into Commt SDKs.

How can I help you? 😇

01:14 PM