Skip to main content
{
  "component": "CometChatCompactMessageComposer",
  "package": "@cometchat/chat-uikit-react",
  "import": "import { CometChatCompactMessageComposer } from \"@cometchat/chat-uikit-react\";",
  "description": "Compact single-line message input with optional rich text formatting (bold, italic, underline, strikethrough, code, links, lists, blockquotes), attachments, mentions, voice recording, and message editing support.",
  "primaryOutput": {
    "prop": "onSendButtonClick",
    "type": "(message: CometChat.BaseMessage) => void"
  },
  "props": {
    "data": {
      "user": { "type": "CometChat.User", "default": "undefined" },
      "group": { "type": "CometChat.Group", "default": "undefined" },
      "parentMessageId": { "type": "number", "default": "undefined" },
      "initialComposerText": { "type": "string", "default": "\"\"" },
      "placeholderText": { "type": "string", "default": "\"Type a message...\"" }
    },
    "callbacks": {
      "onSendButtonClick": "(message: CometChat.BaseMessage) => void",
      "onTextChange": "(text: string) => void",
      "onError": "(error: CometChat.CometChatException) => void"
    },
    "visibility": {
      "hideImageAttachmentOption": { "type": "boolean", "default": false },
      "hideVideoAttachmentOption": { "type": "boolean", "default": false },
      "hideAudioAttachmentOption": { "type": "boolean", "default": false },
      "hideFileAttachmentOption": { "type": "boolean", "default": false },
      "hidePollsOption": { "type": "boolean", "default": false },
      "hideCollaborativeDocumentOption": { "type": "boolean", "default": false },
      "hideCollaborativeWhiteboardOption": { "type": "boolean", "default": false },
      "hideAttachmentButton": { "type": "boolean", "default": false },
      "hideVoiceRecordingButton": { "type": "boolean", "default": false },
      "hideEmojiKeyboardButton": { "type": "boolean", "default": false },
      "hideStickersButton": { "type": "boolean", "default": false },
      "hideSendButton": { "type": "boolean", "default": false }
    },
    "richText": {
      "enableRichTextEditor": { "type": "boolean", "default": false },
      "hideRichTextFormattingOptions": { "type": "boolean", "default": false },
      "showToolbarOnSelection": { "type": "boolean", "default": false },
      "enterKeyBehavior": { "type": "EnterKeyBehavior", "default": "EnterKeyBehavior.SendMessage" }
    },
    "behavior": {
      "disableTypingEvents": { "type": "boolean", "default": false },
      "disableMentions": { "type": "boolean", "default": false },
      "disableMentionAll": { "type": "boolean", "default": false },
      "mentionAllLabel": { "type": "string", "default": "\"all\"" },
      "disableSoundForMessage": { "type": "boolean", "default": false },
      "showScrollbar": { "type": "boolean", "default": false }
    },
    "viewSlots": {
      "headerView": "JSX.Element",
      "auxiliaryButtonView": "JSX.Element",
      "sendButtonView": "JSX.Element"
    },
    "formatting": {
      "textFormatters": {
        "type": "CometChatTextFormatter[]",
        "default": "default formatters from data source"
      },
      "attachmentOptions": {
        "type": "CometChatMessageComposerAction[]",
        "note": "Custom attachment options list (replaces defaults)"
      }
    }
  },
  "events": [
    {
      "name": "ccMessageSent",
      "payload": "{ message: CometChat.BaseMessage, status: string }",
      "description": "Triggers when a message is sent with status: inProgress, success, or error"
    },
    {
      "name": "ccMessageEdited",
      "payload": "{ message: CometChat.BaseMessage, status: string }",
      "description": "Triggers when a message is edited with status: inProgress, success, or error"
    },
    {
      "name": "ccReplyToMessage",
      "payload": "{ message: CometChat.BaseMessage, status: string }",
      "description": "Triggers when a user replies to a message with status: inProgress, success, or error"
    }
  ],
  "compositionExample": {
    "description": "Compact message composer wired with message header and list for complete chat view",
    "components": [
      "CometChatMessageHeader",
      "CometChatMessageList",
      "CometChatCompactMessageComposer"
    ],
    "flow": "Pass user or group prop to composer -> onSendButtonClick fires with CometChat.BaseMessage -> message appears in MessageList"
  }
}

Overview

CometChatCompactMessageComposer is a Component that provides a compact, single-line message input with optional rich text formatting capabilities. It supports bold, italic, underline, strikethrough, code, links, lists, and blockquotes. This is a compact variant of CometChatMessageComposer. It shares a similar props API but provides a streamlined, single-line interface with rich text formatting controls. Wire it alongside CometChatMessageHeader and CometChatMessageList to build a standard chat view. Features such as Rich Text Formatting, Attachments, Message Editing, Mentions, Link Previews, and Voice Recording are supported.
Before using this component: Ensure CometChatUIKit.init(UIKitSettings) has completed and the user is logged in via CometChatUIKit.login("UID"). See React.js Integration.
Available via: UI Kits | SDK

Minimal Render

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

function CompactComposerDemo() {
  return <CometChatCompactMessageComposer user={chatUser} />;
}

export default CompactComposerDemo;

Usage

Integration

The following code snippet illustrates how you can directly incorporate the CompactMessageComposer component into your app.
import React from "react";
import { CometChat } from "@cometchat/chat-sdk-javascript";
import { CometChatCompactMessageComposer } from "@cometchat/chat-uikit-react";

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

  return chatUser ? (
    <div>
      <CometChatCompactMessageComposer user={chatUser} />
    </div>
  ) : null;
}
Expected result:
  • The CometChatCompactMessageComposer component renders a compact, single-line message input
  • The input supports typing, sending messages, attachments, emoji, stickers, and voice recording
  • Clicking the send button dispatches the message to the specified user

Actions and Events

Callback Props

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.

onSendButtonClick

Fires when the send message button is clicked. Overrides the default send behavior.
onSendButtonClick?: (message: CometChat.BaseMessage) => void
import React from "react";
import { CometChat } from "@cometchat/chat-sdk-javascript";
import { CometChatCompactMessageComposer } from "@cometchat/chat-uikit-react";

export function CompactComposerDemo() {
  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 button click action");
  }

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

onError

Fires on internal errors (network failure, auth issue, SDK exception). This action doesn’t change the behavior of the component but rather listens for any errors that occur in the CompactMessageComposer component.
onError?: (error: CometChat.CometChatException) => void
import React from "react";
import { CometChat } from "@cometchat/chat-sdk-javascript";
import { CometChatCompactMessageComposer } from "@cometchat/chat-uikit-react";

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

onTextChange

Fires as the user types in the composer input.
onTextChange?: (text: string) => void
import React from "react";
import { CometChat } from "@cometchat/chat-sdk-javascript";
import { CometChatCompactMessageComposer } from "@cometchat/chat-uikit-react";

export function CompactComposerDemo() {
  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>
      <CometChatCompactMessageComposer
        user={chatUser}
        onTextChange={handleTextChange}
      />
    </div>
  ) : null;
}

Custom Mentions Request Builders

You can customize how mentioned users and group members are fetched by providing custom request builders.
import React from "react";
import { CometChat } from "@cometchat/chat-sdk-javascript";
import { CometChatCompactMessageComposer } from "@cometchat/chat-uikit-react";

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

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

  // Custom Users Request Builder for mentions
  const mentionsUsersRequestBuilder = new CometChat.UsersRequestBuilder()
    .setLimit(10)
    .setSearchKeyword("")
    .setRoles(["default", "moderator"]);

  // Custom Group Members Request Builder for group mentions
  const mentionsGroupMembersRequestBuilder = new CometChat.GroupMembersRequestBuilder("guid")
    .setLimit(15)
    .setSearchKeyword("")
    .setScopes(["admin", "moderator", "participant"]);

  return chatUser ? (
    <div>
      {/* For user chat with custom users mentions */}
      <CometChatCompactMessageComposer
        user={chatUser}
        mentionsUsersRequestBuilder={mentionsUsersRequestBuilder}
      />

      {/* For group chat with custom group members mentions */}
      {chatGroup && (
        <CometChatCompactMessageComposer
          group={chatGroup}
          mentionsGroupMembersRequestBuilder={mentionsGroupMembersRequestBuilder}
        />
      )}
    </div>
  ) : null;
}

Filters

CompactMessageComposer component does not have any available filters.

Global UI Events

Events are emitted by a Component. By using events you can extend existing functionality. Being global events, they can be applied in multiple locations and are capable of being added or removed. CometChatMessageEvents emits events subscribable from anywhere in the application. Add listeners and remove them on cleanup.
EventFires whenPayload
ccMessageSentA message is sent{ message: CometChat.BaseMessage, status: string }
ccMessageEditedA message is edited{ message: CometChat.BaseMessage, status: string }
ccReplyToMessageA user replies to a message{ message: CometChat.BaseMessage, status: string }
Each event has three states: inProgress, success, and error. When to use: sync external UI with message state changes. For example, update a notification badge when messages are sent, or trigger analytics when a message is edited.
import React, { useEffect } from "react";
import { CometChatMessageEvents } from "@cometchat/chat-uikit-react";

function useCompactComposerEvents() {
  useEffect(() => {
    const ccMessageEdited = CometChatMessageEvents.ccMessageEdited.subscribe(
      (item) => {
        console.log("Message edited:", item);
      }
    );

    const ccReplyToMessage = CometChatMessageEvents.ccReplyToMessage.subscribe(
      (item) => {
        console.log("Reply to message:", item);
      }
    );

    const ccMessageSent = CometChatMessageEvents.ccMessageSent.subscribe(
      (item) => {
        console.log("Message sent:", item);
      }
    );

    // Cleanup on unmount
    return () => {
      ccMessageEdited?.unsubscribe();
      ccReplyToMessage?.unsubscribe();
      ccMessageSent?.unsubscribe();
    };
  }, []);
}
In React 18 StrictMode, useEffect runs twice on mount in development. The component handles listener cleanup internally, but any additional listeners added alongside the component need cleanup in the useEffect return function to avoid duplicate event handling.

Customization

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

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

<CometChatCompactMessageComposer user={chatUser} disableTypingEvents={true} />;
Below is a list of customizations along with corresponding code snippets
PropertyTypeDefaultDescriptionCode
userCometChat.UserundefinedSpecifies the recipient of the message (user object).user={chatUser}
groupCometChat.GroupundefinedSpecifies the group to send messages to. Used if the user prop is not provided.group={chatGroup}
parentMessageIdnumberundefinedSpecifies the ID of the parent message for threading or replying to a specific message.parentMessageId={12345}
initialComposerTextstring""The initial text pre-filled in the message input when the component mounts.initialComposerText="Hello"
placeholderTextstring"Type a message..."The placeholder text displayed in the message input when it is empty.placeholderText="Type a message..."
disableTypingEventsbooleanfalseDisables the typing indicator for the current message composer.disableTypingEvents={true}
disableMentionsbooleanfalseDisables the mentions functionality in the message composer.disableMentions={true}
disableMentionAllbooleanfalseControls whether group mentions like @all appear in suggestions.disableMentionAll={true}
mentionAllLabelstring"all"Allows setting a custom alias label for group mentions (@channel, @everyone, etc.).mentionAllLabel="all"
mentionsUsersRequestBuilderCometChat.UsersRequestBuilderundefinedProvides a custom UsersRequestBuilder to control how the mentioned users list is fetched.mentionsUsersRequestBuilder={usersRequestBuilder}
mentionsGroupMembersRequestBuilderCometChat.GroupMembersRequestBuilderundefinedProvides a custom GroupMembersRequestBuilder to customize how mentioned group members are retrieved.mentionsGroupMembersRequestBuilder={groupMembersRequestBuilder}
enableRichTextEditorbooleanfalseMaster switch to enable rich text formatting. When false, the composer works as plain text only.enableRichTextEditor={true}
showToolbarOnSelectionbooleanfalseShows a floating toolbar when text is selected. Ignored on mobile devices.showToolbarOnSelection={true}
hideRichTextFormattingOptionsbooleanfalseHides the rich text formatting toolbar. Keyboard shortcuts still work.hideRichTextFormattingOptions={true}
hideImageAttachmentOptionbooleanfalseHides the image attachment option in the message composer.hideImageAttachmentOption={true}
hideVideoAttachmentOptionbooleanfalseHides the video attachment option in the message composer.hideVideoAttachmentOption={true}
hideAudioAttachmentOptionbooleanfalseHides the audio attachment option in the message composer.hideAudioAttachmentOption={true}
hideFileAttachmentOptionbooleanfalseHides the file attachment option in the message composer.hideFileAttachmentOption={true}
hidePollsOptionbooleanfalseHides the polls option in the message composer.hidePollsOption={true}
hideCollaborativeDocumentOptionbooleanfalseHides the collaborative document option in the message composer.hideCollaborativeDocumentOption={true}
hideCollaborativeWhiteboardOptionbooleanfalseHides the collaborative whiteboard option in the message composer.hideCollaborativeWhiteboardOption={true}
hideAttachmentButtonbooleanfalseHides the attachment button in the message composer.hideAttachmentButton={true}
hideVoiceRecordingButtonbooleanfalseHides the voice recording button in the message composer.hideVoiceRecordingButton={true}
hideEmojiKeyboardButtonbooleanfalseHides the emoji keyboard button in the message composer.hideEmojiKeyboardButton={true}
hideStickersButtonbooleanfalseHides the stickers button in the message composer.hideStickersButton={true}
hideSendButtonbooleanfalseHides the send button in the message composer.hideSendButton={true}
showScrollbarbooleanfalseControls the visibility of the scrollbar in the composer.showScrollbar={true}
enterKeyBehaviorEnterKeyBehaviorEnterKeyBehavior.SendMessageDetermines the behavior of the Enter key (e.g., send message or add a new line).enterKeyBehavior={EnterKeyBehavior.SendMessage}
disableSoundForMessagebooleanfalseDisables sound for incoming messages.disableSoundForMessage={true}
customSoundForMessagestringundefinedSpecifies a custom audio sound for incoming messages.customSoundForMessage="sound.mp3"

Rich Text Formatting

The CompactMessageComposer includes a built-in rich text editor. Rich text must be explicitly enabled via enableRichTextEditor={true} (defaults to false).

Formatting Toolbar

The toolbar provides the following formatting tools in a fixed order:
ToolIconShortcutDescription
BoldBCmd/Ctrl+BBold text
ItalicICmd/Ctrl+IItalic text
UnderlineUCmd/Ctrl+UUnderline text
StrikethroughSCmd/Ctrl+Shift+SStrikethrough text
Inline Code</>Cmd/Ctrl+EInline code
Code Block```Cmd/Ctrl+Shift+CMulti-line code block
Link🔗Cmd/Ctrl+KAdd/edit hyperlink
Bullet ListCmd/Ctrl+Shift+8Unordered list
Ordered List1.Cmd/Ctrl+Shift+7Numbered list
BlockquoteCmd/Ctrl+Shift+9Quote block

Toolbar Visibility Modes

The toolbar supports multiple display modes controlled via props. When multiple props are set, they follow this priority order:
  1. enableRichTextEditor={false} — Highest priority, disables all rich text features (plain text only)
  2. hideRichTextFormattingOptions={true} — Toolbar visible by default above input
  3. showToolbarOnSelection={true} — Floating toolbar appears on text selection (desktop only)
If none of the toolbar props are enabled, the toolbar is hidden but keyboard shortcuts still work.

Behavior Matrix

enableRichTextEditorhideRichTextFormattingOptionsshowToolbarOnSelectionResult
false--Plain text, no formatting UI
truefalsetrueFloating toolbar appears on text selection (desktop)
truetruefalseToolbar visible by default above input
truefalsefalseNo toolbar UI, only keyboard shortcuts work

Mobile Behavior

On mobile devices, only the fixed toolbar is supported. The floating selection toolbar is disabled for better touch UX.
PropsMobile Behavior
showToolbarOnSelection={true}Ignored on mobile — Falls back to fixed toolbar
hideRichTextFormattingOptions={true}Fixed toolbar visible by default above input

Toolbar Configuration Examples

// Floating toolbar appears on text selection (desktop only)
<CometChatCompactMessageComposer
  user={chatUser}
  enableRichTextEditor={true}
  showToolbarOnSelection={true}
/>

Custom View Slots

Each slot replaces a section of the default UI. Slots that accept parameters receive the relevant data for customization.
SlotTypeReplaces
headerViewJSX.ElementArea above the composer input
auxiliaryButtonViewJSX.ElementSticker and AI button area
sendButtonViewJSX.ElementSend button
attachmentOptionsCometChatMessageComposerAction[]Default attachment options list (replaces defaults)
textFormattersCometChatTextFormatter[]Text formatting in composer

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 CompactMessageComposer Component. This will override the existing list of MessageComposerActions.
Use the following code to achieve the customization shown above.
import React from "react";
import { CometChat } from "@cometchat/chat-sdk-javascript";
import {
  CometChatCompactMessageComposer,
  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",
    }),
  ];
}

<CometChatCompactMessageComposer
  attachmentOptions={getAttachments()}
  user={userObj}
/>;
Expected result: The default attachment options (image, video, audio, file, polls, etc.) are replaced with four custom options. The action sheet styling is customized with transparent background and custom icon colors.

AuxiliaryButtonView

You can insert a custom view into the CompactMessageComposer component to add additional functionality using the following method.
The CompactMessageComposer Component utilizes the AuxiliaryButton to provide sticker and AI functionality. Overriding the AuxiliaryButton will subsequently replace the sticker functionality.
import React from "react";
import { CometChat } from "@cometchat/chat-sdk-javascript";
import {
  CometChatCompactMessageComposer,
  CometChatButton,
} from "@cometchat/chat-uikit-react";

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

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

SendButtonView

You can set a custom view in place of the already existing send button view.
import React from "react";
import { CometChat } from "@cometchat/chat-sdk-javascript";
import {
  CometChatCompactMessageComposer,
  CometChatButton,
} from "@cometchat/chat-uikit-react";

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

<CometChatCompactMessageComposer sendButtonView={sendButtonView} user={userObj} />;
Expected result: The default send button is replaced with a custom button. The CSS overrides give the button a light purple background (#edeafa) with a purple icon (#6852d6).

HeaderView

You can set custom headerView to the CompactMessageComposer component using the following method.
import React from "react";
import { CometChat } from "@cometchat/chat-sdk-javascript";
import { CometChatCompactMessageComposer } from "@cometchat/chat-uikit-react";

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

<CometChatCompactMessageComposer user={chatUser} headerView={getHeaderView()} />;
Expected result: A custom header bar appears above the composer input with an icon and notification text (“User has paused their notifications”), styled with a light purple background and rounded corners.

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;

  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) {
        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();
    this.dialogIsOpen = false;
    this.currentShortcut = null;
  }

  handleButtonClick = (buttonText: string) => {
    if (this.currentCaretPosition && this.currentRange) {
      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;


Next Steps

Message Composer

Full-featured multi-line message composer component.

Message List

Display messages with real-time updates.

Mentions Formatter

Implement @mentions in your chat application.

Theme Customization

Customize colors, fonts, and styling.