Skip to main content
Version: v5

Message Composer

Overview

MessageComposer is a Component that enables users to write and send a variety of messages, including text, image, video, and custom messages.

Features such as Attachments, and Message Editing are also supported by it.

Image

Usage

Integration

The following code snippet illustrates how you can directly incorporate the MessageComposer component into your app.

import React from "react";
import { CometChat } from "@cometchat/chat-sdk-javascript";
import { CometChatMessageComposer } from "@cometchat/chat-uikit-react";

export function MessageComposerDemo() {
const [chatUser, setChatUser] = React.useState<CometChat.User>();
React.useEffect(() => {
CometChat.getUser("uid").then((user) => {
setChatUser(user);
});
}, []);

return chatUser ? (
<div>
<CometChatMessageComposer user={chatUser} />
</div>
) : null;
}

Actions

Actions dictate how a component functions. They are divided into two types: Predefined and User-defined. You can override either type, allowing you to tailor the behavior of the component to fit your specific needs.

1. OnSendButtonClick

The OnSendButtonClick event gets activated when the send message button is clicked. It has a predefined function of sending messages entered in the composer EditText. However, you can overide this action with the following code snippet.

import React from "react";
import { CometChat } from "@cometchat/chat-sdk-javascript";
import { CometChatMessageComposer } from "@cometchat/chat-uikit-react";

export function MessageComposerDemo() {
const [chatUser, setChatUser] = React.useState<CometChat.User>();

React.useEffect(() => {
CometChat.getUser("uid").then((user) => {
setChatUser(user);
});
}, []);

function handleSendButtonClick(message: CometChat.BaseMessage): void {
console.log("your custom on send buttonclick action");
}

return chatUser ? (
<div>
<CometChatMessageComposer onSendButtonClick={handleSendButtonClick} />
</div>
) : null;
}
2. onError

This action doesn't change the behavior of the component but rather listens for any errors that occur in the MessageList component.

import React from "react";
import { CometChat } from "@cometchat/chat-sdk-javascript";
import { CometChatMessageComposer } from "@cometchat/chat-uikit-react";

export function MessageComposerDemo() {
const [chatUser, setChatUser] = React.useState<CometChat.User>();

React.useEffect(() => {
CometChat.getUser("uid").then((user) => {
setChatUser(user);
});
}, []);

function handleError(error: CometChat.CometChatException) {
throw new Error("your custom error action");
}

return chatUser ? (
<div>
<CometChatMessageComposer user={chatUser} onError={handleError} />
</div>
) : null;
}
3. onTextChange

This event is triggered as the user starts typing in the Message Composer.

import React from "react";
import { CometChat } from "@cometchat/chat-sdk-javascript";
import { CometChatMessageComposer } from "@cometchat/chat-uikit-react";

export function MessageComposerDemo() {
const [chatUser, setChatUser] = React.useState<CometChat.User>();

React.useEffect(() => {
CometChat.getUser("uid").then((user) => {
setChatUser(user);
});
}, []);

function handleTextChange(text: string) {
console.log("onTextChange", text);
}

return chatUser ? (
<div>
<CometChatMessageComposer
user={chatUser}
onTextChange={handleTextChange}
/>
</div>
) : null;
}

Filters

MessageComposer component does not have any available filters.


Events

Events are emitted by a Component. By using event you can extend existing functionality. Being global events, they can be applied in Multiple Locations and are capable of being Added or Removed.

The list of events emitted by the Messages component is as follows.

EventDescription
ccMessageEditedTriggers whenever a loggedIn user edits any message from the list of messages .it will have three states such as: inProgress, success and error.
ccMessageSentTriggers whenever a loggedIn user sends any message, it will have three states such as: inProgress, success and error.

Adding CometChatMessageEvents Listener's

import { CometChatMessageEvents } from "@cometchat/chat-uikit-react";

const ccMessageEdited = CometChatMessageEvents.ccMessageEdited.subscribe(() => {
// Your Code
});

const ccMessageSent = CometChatMessageEvents.ccMessageSent.subscribe(() => {
// Your Code
});

Removing CometChatMessageEvents Listener's

ccMessageEdited?.unsubscribe();
ccMessageSent?.unsubscribe();

Customization

To fit your app's design requirements, you can customize the appearance of the MessageComposer component. We provide exposed methods that allow you to modify the experience and behavior according to your specific needs.

Style

To modify the styling, you can customise the css of MessageComposer Component.

Example

Image
import React from "react";
import { CometChat } from "@cometchat/chat-sdk-javascript";
import { CometChatMessageComposer } from "@cometchat/chat-uikit-react";

<CometChatMessageComposer user={chatUser} />;

Functionality

These are a set of small functional customizations that allow you to fine-tune the overall experience of the component. With these, you can change text, set custom icons, and toggle the visibility of UI elements.

import React from "react";
import { CometChat } from "@cometchat/chat-sdk-javascript";
import { CometChatMessageComposer } from "@cometchat/chat-uikit-react";

<CometChatMessageComposer user={chatUser} disableTypingEvents={true} />;

Below is a list of customizations along with corresponding code snippets

PropertyDescriptionCode
Initial Composer TextThe initial text pre-filled in the message input when the component mounts.initialComposerText="Hello"
Disable Typing EventsDisables the typing indicator for the current message composer.disableTypingEvents={true}
Disable MentionsDisables the mentions functionality in the message composer.disableMentions={true}
Hide Image Attachment OptionHides the image attachment option in the message composer.hideImageAttachmentOption={true}
Hide Video Attachment OptionHides the video attachment option in the message composer.hideVideoAttachmentOption={true}
Hide Audio Attachment OptionHides the audio attachment option in the message composer.hideAudioAttachmentOption={true}
Hide File Attachment OptionHides the file attachment option in the message composer.hideFileAttachmentOption={true}
Hide Polls OptionHides the polls option in the message composer.hidePollsOption={true}
Hide Collaborative DocumentHides the collaborative document option in the message composer.hideCollaborativeDocumentOption={true}
Hide Collaborative WhiteboardHides the collaborative whiteboard option in the message composer.hideCollaborativeWhiteboardOption={true}
Hide Attachment ButtonHides the attachment button in the message composer.hideAttachmentButton={true}
Hide Voice Recording ButtonHides the voice recording button in the message composer.hideVoiceRecordingButton={true}
Hide Emoji Keyboard ButtonHides the emoji keyboard button in the message composer.hideEmojiKeyboardButton={true}
Hide Stickers ButtonHides the stickers button in the message composer.hideStickersButton={true}
Hide Send ButtonHides the send button in the message composer.hideSendButton={true}
UserSpecifies the recipient of the message (user object).user={chatUser}
GroupSpecifies the group to send messages to. Used if the user prop is not provided.group={chatGroup}
Parent Message IDSpecifies the ID of the parent message for threading or replying to a specific message.parentMessageId={12345}
Enter Key BehaviorDetermines the behavior of the Enter key (e.g., send message or add a new line).enterKeyBehavior={EnterKeyBehavior.SendMessage}
Disable Sound for MessageDisables sound for incoming messages.disableSoundForMessage={true}
Custom Sound for MessageSpecifies a custom audio sound for incoming messages.customSoundForMessage="sound.mp3"

Advanced

For advanced-level customization, you can set custom views to the component. This lets you tailor each aspect of the component to fit your exact needs and application aesthetics. You can create and define your views, layouts, and UI elements and then incorporate those into the component.


AttachmentOptions

By using attachmentOptions, you can set a list of custom MessageComposerActions for the MessageComposer Component. This will override the existing list of MessageComposerActions.

Shown below is the default chat interface.

Image

The customized chat interface is displayed below.

Image

Use the following code to achieve the customization shown above.

import React from "react";
import { CometChat } from "@cometchat/chat-sdk-javascript";
import {
CometChatMessageComposer,
CometChatMessageComposerAction,
} from "@cometchat/chat-uikit-react";

function getAttachments() {
return [
new CometChatMessageComposerAction({
id: "custom1",
title: "Custom Option 1",
iconURL: "Icon URL",
}),
new CometChatMessageComposerAction({
id: "custom2",
title: "Custom Option 2",
iconURL: "Icon URL",
}),
new CometChatMessageComposerAction({
id: "custom3",
title: "Custom Option 3",
iconURL: "Icon URL",
}),
new CometChatMessageComposerAction({
id: "custom4",
title: "Custom Option 4",
iconURL: "Icon URL",
}),
];
}

<CometChatMessageComposer
attachmentOptions={getAttachments()}
user={userObj}
/>;

AuxiliaryButtonView

You can insert a custom view into the MessageComposer component to add additional functionality using the following method.

Please note that the MessageComposer Component utilizes the AuxiliaryButton to provide sticker and AI functionality. Overriding the AuxiliaryButton will subsequently replace the sticker functionality.

Shown below is the default chat interface.

Image

The customized chat interface is displayed below.

Image

Use the following code to achieve the customization shown above.

import React from "react";
import { CometChat } from "@cometchat/chat-sdk-javascript";
import {
CometChatMessageComposer,
IconStyle,
CometChatButton,
} from "@cometchat/chat-uikit-react";

const auxiliaryButtonView = (
<CometChatButton
iconURL="Icon URL"
onClick={() => {
// logic here
}}
/>
);

<CometChatMessageComposer
auxiliaryButtonView={auxiliaryButtonView}
user={userObj}
/>;

SendButtonView

You can set a custom view in place of the already existing send button view.

Shown below is the default chat interface.

Image

The customized chat interface is displayed below.

Image

Use the following code to achieve the customization shown above.

import React from "react";
import { CometChat } from "@cometchat/chat-sdk-javascript";
import {
CometChatMessageComposer,
CometChatButton,
} from "@cometchat/chat-uikit-react";

const sendButtonView = (
<CometChatButton
iconURL="Icon URL"
onClick={() => {
// logic here
}}
/>
);

<CometChatMessageComposer sendButtonView={sendButtonView} user={userObj} />;

HeaderView

You can set custom headerView to the MessageComposer component using the following method.

Shown below is the default chat interface.

Image

The customized chat interface is displayed below.

Image

Use the following code to achieve the customization shown above.

import React from "react";
import { CometChat } from "@cometchat/chat-sdk-javascript";
import { CometChatMessageComposer } from "@cometchat/chat-uikit-react";

const getHeaderView = () => {
return (
<div className="message-composer__header-view">
<div className="message-composer__header-view-icon"></div>
<div className="message-composer__header-view-text">
User has paused their notifications
</div>
</div>
);
};

<CometChatMessageComposer user={chatUser} headerView={getHeaderView()} />;

TextFormatters

Assigns the list of text formatters. If the provided list is not null, it sets the list. Otherwise, it assigns the default text formatters retrieved from the data source. To configure the existing Mentions look and feel check out CometChatMentionsFormatter

import { CometChatTextFormatter } from "@cometchat/chat-uikit-react";
import DialogHelper from "./Dialog";
import { CometChat } from "@cometchat/chat-sdk-javascript";

class ShortcutFormatter extends CometChatTextFormatter {
private shortcuts: { [key: string]: string } = {};
private dialogIsOpen: boolean = false;
private dialogHelper = new DialogHelper();
private currentShortcut: string | null = null; // Track the currently open shortcut

constructor() {
super();
this.setTrackingCharacter("!");
CometChat.callExtension("message-shortcuts", "GET", "v1/fetch", undefined)
.then((data: any) => {
if (data && data.shortcuts) {
this.shortcuts = data.shortcuts;
}
})
.catch((error) => console.log("error fetching shortcuts", error));
}

onKeyDown(event: KeyboardEvent) {
const caretPosition =
this.currentCaretPosition instanceof Selection
? this.currentCaretPosition.anchorOffset
: 0;
const textBeforeCaret = this.getTextBeforeCaret(caretPosition);

const match = textBeforeCaret.match(/!([a-zA-Z]+)$/);
if (match) {
const shortcut = match[0];
const replacement = this.shortcuts[shortcut];
if (replacement) {
// Close the currently open dialog, if any
if (this.dialogIsOpen && this.currentShortcut !== shortcut) {
this.closeDialog();
}
this.openDialog(replacement, shortcut);
}
}
}

getCaretPosition() {
if (!this.currentCaretPosition?.rangeCount) return { x: 0, y: 0 };
const range = this.currentCaretPosition?.getRangeAt(0);
const rect = range.getBoundingClientRect();
return {
x: rect.left,
y: rect.top,
};
}

openDialog(buttonText: string, shortcut: string) {
this.dialogHelper.createDialog(
() => this.handleButtonClick(buttonText),
buttonText
);
this.dialogIsOpen = true;
this.currentShortcut = shortcut;
}

closeDialog() {
this.dialogHelper.closeDialog(); // Use DialogHelper to close the dialog
this.dialogIsOpen = false;
this.currentShortcut = null;
}

handleButtonClick = (buttonText: string) => {
if (this.currentCaretPosition && this.currentRange) {
// Inserting the replacement text corresponding to the shortcut
const shortcut = Object.keys(this.shortcuts).find(
(key) => this.shortcuts[key] === buttonText
);
if (shortcut) {
const replacement = this.shortcuts[shortcut];
this.addAtCaretPosition(
replacement,
this.currentCaretPosition,
this.currentRange
);
}
}
if (this.dialogIsOpen) {
this.closeDialog();
}
};

getFormattedText(text: string): string {
return text;
}

private getTextBeforeCaret(caretPosition: number): string {
if (
this.currentRange &&
this.currentRange.startContainer &&
typeof this.currentRange.startContainer.textContent === "string"
) {
const textContent = this.currentRange.startContainer.textContent;
if (textContent.length >= caretPosition) {
return textContent.substring(0, caretPosition);
}
}
return "";
}
}

export default ShortcutFormatter;