Skip to main content
Version: v5

Message List

Overview

MessageList is a composite component that displays a list of messages and effectively manages real-time operations. It includes various types of messages such as Text Messages, Media Messages, Stickers, and more.

Image

Usage

Integration

The following code snippet illustrates how you can directly incorporate the MessageList component into your Application.

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

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

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

To fetch messages for a specific entity, you need to supplement it with User or Group Object.


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. onThreadRepliesClick

onThreadRepliesClick is triggered when you click on the threaded message bubble. The onThreadRepliesClick action doesn't have a predefined behavior. You can override this action using the following code snippet.

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

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

const getOnThreadRepliesClick = () => {
//your custom actions
};

return chatUser ? (
<div>
<CometChatMessageList
user={chatUser}
onThreadRepliesClick={getOnThreadRepliesClick}
/>
</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 { CometChatMessageList } from "@cometchat/chat-uikit-react";

export function MessageListDemo() {
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>
<CometChatMessageList user={chatUser} onError={handleError} />
</div>
) : null;
}

Filters

You can adjust the MessagesRequestBuilder in the MessageList Component to customize your message list. Numerous options are available to alter the builder to meet your specific needs. For additional details on MessagesRequestBuilder, please visit MessagesRequestBuilder.

In the example below, we are applying a filter to the messages based on a search substring and for a specific user. This means that only messages that contain the search term and are associated with the specified user will be displayed

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

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

return chatUser ? (
<div>
<CometChatMessageList
user={chatUser}
messagesRequestBuilder={new CometChat.MessagesRequestBuilder().setLimit(
5
)}
/>
</div>
) : null;
}
info

The following parameters in messageRequestBuilder will always be altered inside the message list

  1. UID
  2. GUID

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 Message List component is as follows.

EventDescription
ccOpenChatthis event alerts the listeners if the logged-in user has opened a user or a group chat.
ccMessageEditedTriggers whenever a loggedIn user edits any message from the list of messages .it will have three states such as: inProgress, success and error.
ccMessageDeletedTriggers whenever a loggedIn user deletes any message from the list of messages.
ccActiveChatChangedThis event is triggered when the user navigates to a particular chat window.
ccMessageReadTriggers whenever a loggedIn user reads any message.

Adding CometChatMessageEvents Listener's

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

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

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

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

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

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

Removing CometChatMessageEvents Listener's

ccMessageEdited?.unsubscribe();
ccActiveChatChanged?.unsubscribe();

Customization

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

Style

You can set the css to the MessageList Component Component to customize the styling.

Example

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

<CometChatMessageList 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 { CometChatMessageList } from "@cometchat/chat-uikit-react";

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

return chatUser ? (
<div>
<CometChatMessageList
user={chatUser}
hideError={true}
hideReceipt={true}
/>
</div>
) : null;
}

Below is a list of customizations along with corresponding code snippets

PropertyDescriptionCode
Hide Conversation StartersHides the visibility of the conversation starters in the message list.hideConversationStarters={true}
Hide Smart RepliesHides the visibility of the smart replies in the message list.hideSmartReplies={true}
Smart Replies KeywordsSets the keywords on which the smart replies should be triggered in the message list.smartRepliesKeywords={['why', 'how']}
Smart Replies Delay DurationSets the delay duration (in milliseconds) before smart replies are shown.smartRepliesDelayDuration={5000}
Hide Date SeparatorHides the visibility of the date separator in the message list.hideDateSeparator={true}
Hide Sticky DateHides the sticky date header in the message list.hideStickyDate={true}
Hide ReceiptsHides the visibility of receipts in the message list.hideReceipts={true}
Hide ErrorHides the default & custom error view passed in the errorView prop.hideError={true}
Hide Reply In Thread OptionHides the option to reply to messages in a thread.hideReplyInThreadOption={true}
Hide Translate Message OptionHides the option to translate messages.hideTranslateMessageOption={true}
Hide Edit Message OptionHides the option to edit messages.hideEditMessageOption={true}
Hide Delete Message OptionHides the option to delete messages.hideDeleteMessageOption={true}
Hide Reaction OptionHides the option to react to messages.hideReactionOption={true}
Hide Message Privately OptionHides the option to message a user privately.hideMessagePrivatelyOption={true}
Hide Copy Message OptionHides the option to copy messages.hideCopyMessageOption={true}
Hide Message Info OptionHides the option to view message information.hideMessageInfoOption={true}
Hide AvatarHides avatars for messages.hideAvatar={true}
Hide Group Action MessagesHides group action messages.hideGroupActionMessages={true}
Parent Message IDUnique identifier of the parent message for displaying threaded conversations.parentMessageId={1234}
UserA CometChat.User object representing the participant of the chat.user={chatUser}
GroupA CometChat.Group object representing the group whose chat messages are displayed.group={chatGroup}
Reactions Request BuilderInstance of the CometChat.ReactionsRequestBuilder for managing message reactions.reactionsRequestBuilder={reactionBuilder}
Message AlignmentSpecifies the alignment of messages in the list (e.g., left, right).messageAlignment={MessageListAlignment.left}
Scroll To Bottom On New MessagesAutomatically scrolls the message list to the bottom when a new message arrives.scrollToBottomOnNewMessages={true}
Quick Options CountSpecifies how many message options are visible in the main menu by default.quickOptionsCount={3}
Disable Sound For MessagesDisables the sound effect when new messages arrive.disableSoundForMessages={true}
Custom Sound For MessagesSpecifies a custom sound file to play when new messages arrive.customSoundForMessages="sound.mp3"
On Reaction ClickCallback function triggered when a reaction is clicked.onReactionClick={(reaction, msg) => handleReaction}
On Reaction List Item ClickCallback function triggered when an item in the reaction list is clicked.onReactionListItemClick={handleReactionItem}
Empty ViewCustom empty state view to display when there are no messages.emptyView={<EmptyState />}
Error ViewA custom view displayed when there are no messages.errorView={<ErrorComponent />}
Loading ViewA custom view displayed while messages are being fetched.loadingView={<LoadingSpinner />}

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.

Templates

CometChatMessageTemplate is a pre-defined structure for creating message views that can be used as a starting point or blueprint for creating message views often known as message bubbles. For more information, you can refer to CometChatMessageTemplate.

You can set message Templates to MessageList by using the following code snippet.

import React from "react";
import { CometChat } from "@cometchat/chat-sdk-javascript";
import {
CometChatMessageList,
CometChatMessageOption,
CometChatTheme,
ChatConfigurator,
} from "@cometchat/chat-uikit-react";

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

const getCustomOptions = (
loggedInUser: CometChat.User,
message: CometChat.BaseMessage,
theme: CometChatTheme,
group?: CometChat.Group
) => {
const defaultOptions: any =
ChatConfigurator.getDataSource().getMessageOptions(
loggedInUser,
message,
theme,
group
);
const myView: any = new CometChatMessageOption({
id: "custom id",
title: "your custom title for options",
iconURL: "your custom icon url for options",
iconTint: "#7316f5",
onClick: () => console.log("custom action"),
});
defaultOptions.push(myView);
return defaultOptions;
};

const getTemplates = () => {
let templates = ChatConfigurator.getDataSource().getAllMessageTemplates();
templates.map((data) => {
data.options = (
loggedInUser: CometChat.User,
message: CometChat.BaseMessage,
theme: CometChatTheme,
group?: CometChat.Group
) => getCustomOptions(loggedInUser, message, theme, group);
});
return templates;
};

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

DatePattern

You can customize the date pattern of the message list separator using the DatePattern prop. Choose from predefined options like time, DayDate, DayDateTime, or DateTime.

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

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

return chatUser ? (
<div>
<CometChatMessageList
user={chatUser}
datePattern={DatePatterns.DateTime}
/>
</div>
) : null;
}

TimePattern

You can modify the date pattern to your requirement using TimePattern. Choose from predefined options like time, DayDate, DayDateTime, or DateTime.

TimePatterns describes a specific format or arrangement used to represent dates in a human-readable form.

NameDescription
timeDate format displayed in the format hh:mm a
DayDateDate format displayed in the following format.
  1. If timestamp < 24hrs display “Today”
  2. If timestamp < 48hrs display “Yesterday”
  3. If timestamp < 7days display “EEE” i.e , SUNDAY
  4. else display “d MMM, yyyy”
DayDateTimeDate format displayed in the following format.
  1. If timestamp < 24hrs display “hh:mm a”
  2. If timestamp < 48hrs display “Yesterday”
  3. If timestamp < 7days display “EEE” i.e SUNDAY
  4. else display “dd MM yyyy”
import React from "react";
import { CometChat } from "@cometchat/chat-sdk-javascript";
import {
CometChatMessageList,
DatePatterns,
} from "@cometchat/chat-uikit-react";

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

return chatUser ? (
<div>
<CometChatMessageList
user={chatUser}
datePattern={DatePatterns.DateTime}
/>
</div>
) : null;
}

Headerview

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

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 { CometChatMessageList } from "@cometchat/chat-uikit-react";
import notesIcon from "../../assets/notesIcon.svg";
import pinnedIcon from "../../assets/pinnedIcon.svg";
import savedIcon from "../../assets/savedIcon.svg";

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

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

const getHeaderView = () => {
return (
<div className="header-view">
<CometChatButton iconURL={notesIcon} text="Notes" />
<CometChatButton iconURL={pinnedIcon} text="Pinned Message" />
<CometChatButton iconURL={savedIcon} text="Saved Links" />
</div>
);
};

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

FooterView

You can set custom footerview to the Message List component using the following method.

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 { CometChatMessageList } from "@cometchat/chat-uikit-react";
import iceBreakersIcon from "../../assets/iceBreakersIcon.svg";
import callIcon from "../../assets/callIcon.svg";
import instagramIcon from "../../assets/instagramIcon.svg";
import snapchatIcon from "../../assets/snapchatIcon.svg";

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

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

const getFooterView = () => {
return (
<div className="footer-view">
<CometChatButton iconURL={iceBreakersIcon} text="Ice Breakers" />
<CometChatButton iconURL={callIcon} text="+1-212-456-7890" />
<CometChatButton iconURL={instagramIcon} text="+ Instagram" />
<CometChatButton iconURL={snapchatIcon} text="+ Snapchat" />
</div>
);
};

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

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;