Skip to main content
FieldValue
Package@cometchat/chat-uikit-react-native
Key classCometChatTextFormatter (abstract base class for custom formatters)
Required setupCometChatUIKit.init(UIKitSettings) then CometChatUIKit.login("UID")
PurposeExtend to create custom inline text patterns with regex, styling, and callbacks
FeaturesText formatting, customizable styles, dynamic text replacement, suggestion list integration
Sample appGitHub
RelatedShortCut Formatter · Mentions Formatter · All Guides
CometChatTextFormatter is an abstract class for formatting text in the message composer and message bubbles. Extend it to build custom formatters — hashtags, keywords, or any regex-based pattern.
CapabilityDescription
Text formattingAuto-format text based on regex patterns and styles
Custom stylesSet colors, fonts, and backgrounds for matched text
Suggestion listDisplay suggestions when tracking character is typed
Message handlingProcess messages before sending with handlePreMessageSend

Base Class Overview

The CometChatTextFormatter class provides the foundation for all text formatters in React Native:
import { CometChatTextFormatter } from "@cometchat/chat-uikit-react-native";

abstract class CometChatTextFormatter {
  protected regexPattern: RegExp;
  protected trackCharacter: string;
  protected loggedInUser?: CometChat.User;
  protected messageObject: CometChat.BaseMessage;
  protected SuggestionItems: Array<SuggestionItem>;
  
  // Core methods
  setTrackingCharacter(char: string): void;
  setRegexPatterns(pattern: RegExp): void;
  getFormattedText(inputText: string | null | JSX.Element): string | null | JSX.Element;
  handlePreMessageSend(message: CometChat.TextMessage): CometChat.TextMessage;
  search(searchKey: string): void;
  fetchNext(): void;
  setSearchData(data: Array<SuggestionItem>): void;
}

Steps

1. Import the base class

import { CometChatTextFormatter, SuggestionItem } from "@cometchat/chat-uikit-react-native";

2. Extend it

class HashTagTextFormatter extends CometChatTextFormatter {
  constructor() {
    super();
    this.setTrackingCharacter("#");
    this.setRegexPatterns(/\B#(\w+)\b/g);
  }
}

3. Implement formatting methods

Override getFormattedText to apply custom styling to matched patterns:
import React from "react";
import { Text } from "react-native";

class HashTagTextFormatter extends CometChatTextFormatter {
  constructor() {
    super();
    this.setTrackingCharacter("#");
    this.setRegexPatterns(/\B#(\w+)\b/g);
  }

  getFormattedText(inputText: string | null | JSX.Element): string | null | JSX.Element {
    if (!inputText || typeof inputText !== "string") {
      return inputText;
    }

    const regex = this.getRegexPattern();
    const parts: (string | JSX.Element)[] = [];
    let lastIndex = 0;
    let match;

    while ((match = regex.exec(inputText)) !== null) {
      // Add text before the match
      if (match.index > lastIndex) {
        parts.push(inputText.slice(lastIndex, match.index));
      }

      // Add styled hashtag
      parts.push(
        <Text key={match.index} style={{ color: "#5dff05", fontWeight: "bold" }}>
          #{match[1]}
        </Text>
      );

      lastIndex = match.index + match[0].length;
    }

    // Add remaining text
    if (lastIndex < inputText.length) {
      parts.push(inputText.slice(lastIndex));
    }

    return <Text>{parts}</Text>;
  }
}

export default HashTagTextFormatter;

Example

A hashtag formatter used with CometChatMessageList and CometChatMessageComposer.
import React, { JSX } from "react";
import { Text, TextStyle } from "react-native";
import { CometChat } from "@cometchat/chat-sdk-react-native";
import { CometChatTextFormatter } from "@cometchat/chat-uikit-react-native";

class HashTagTextFormatter extends CometChatTextFormatter {
  private hashtagStyle: TextStyle = {
    color: "#5dff05",
    fontWeight: "bold",
  };

  constructor() {
    super();
    this.setTrackingCharacter("#");
    this.setRegexPatterns(/\B#(\w+)\b/g);
  }

  setHashtagStyle(style: TextStyle) {
    this.hashtagStyle = style;
  }

  getFormattedText(inputText: string | null | JSX.Element): string | null | JSX.Element {
    if (!inputText || typeof inputText !== "string") {
      return inputText;
    }

    const regex = this.getRegexPattern();
    const parts: (string | JSX.Element)[] = [];
    let lastIndex = 0;
    let match;

    // Reset regex lastIndex for global patterns
    regex.lastIndex = 0;

    while ((match = regex.exec(inputText)) !== null) {
      if (match.index > lastIndex) {
        parts.push(inputText.slice(lastIndex, match.index));
      }

      parts.push(
        <Text key={match.index} style={this.hashtagStyle}>
          #{match[1]}
        </Text>
      );

      lastIndex = match.index + match[0].length;
    }

    if (lastIndex < inputText.length) {
      parts.push(inputText.slice(lastIndex));
    }

    if (parts.length === 0) {
      return inputText;
    }

    return <Text>{parts}</Text>;
  }
}

export default HashTagTextFormatter;

Methods Reference

MethodDescription
setTrackingCharacter(char)Character that starts tracking (e.g. # for hashtags)
setRegexPatterns(pattern)Regex pattern to match text for formatting
getFormattedText(inputText)Returns formatted JSX from input text
handlePreMessageSend(message)Process message before sending
search(searchKey)Search function called when tracking character is typed
fetchNext()Fetch next page of suggestions
setSearchData(data)Set suggestion list data
setSuggestionItems(items)Set the suggestion items array
getSuggestionItems()Get current suggestion items
setMessage(message)Set the message object in context
getMessage()Get the current message object
setUser(user)Set the user in context
setGroup(group)Set the group in context
setLoggedInUser(user)Set the logged-in user
setComposerId(id)Set the composer ID for event handling
setId(id)Set unique identifier for the formatter

Advanced: Suggestion List Integration

For formatters that need to show suggestions (like mentions), implement the search method:
import { CometChat } from "@cometchat/chat-sdk-react-native";
import { CometChatTextFormatter, SuggestionItem } from "@cometchat/chat-uikit-react-native";

class CustomSuggestionFormatter extends CometChatTextFormatter {
  constructor() {
    super();
    this.setTrackingCharacter(":");
  }

  search(searchKey: string): void {
    // Fetch data based on searchKey
    const suggestions = this.filterSuggestions(searchKey);
    
    const suggestionItems = suggestions.map((item) => 
      new SuggestionItem({
        id: item.id,
        name: item.name,
        promptText: `:${item.name}:`,
        trackingCharacter: ":",
        underlyingText: `:${item.code}:`,
      })
    );

    this.setSearchData(suggestionItems);
  }

  private filterSuggestions(searchKey: string): any[] {
    // Your filtering logic here
    return [];
  }
}

Next Steps