> ## Documentation Index
> Fetch the complete documentation index at: https://cometchat-22654f5b-docs-llms-scoped-indexes.mintlify.site/llms.txt
> Use this file to discover all available pages before exploring further.

# Text Formatters

> Extend the CometChatTextFormatter base class to implement custom inline text patterns with regex and callbacks in React Native.

<Accordion title="AI Integration Quick Reference">
  | Field | Value |
  | - | - |
  | Components | `CometChatMessageComposer`, `CometChatMessageHeader`, `CometChatMessageList` |
  | Package | `@cometchat/chat-uikit-react-native` |
  | Key class | `CometChatTextFormatter` (abstract base class for custom formatters) |
  | Required setup | `CometChatUIKit.init(UIKitSettings)` then `CometChatUIKit.login("UID")` |
  | Purpose | Extend to create custom inline text patterns with regex, styling, and callbacks |
  | Features | Text formatting, customizable styles, dynamic text replacement, suggestion list integration |
  | Sample app | [GitHub](https://github.com/cometchat/cometchat-uikit-react-native/tree/v5/sample) |
  | Related | [ShortCut Formatter](/ui-kit/react-native/shortcut-formatter-guide) · [Mentions Formatter](/ui-kit/react-native/mentions-formatter-guide) · [All Guides](/ui-kit/react-native/guide-overview) |
</Accordion>

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

| Capability | Description |
| - | - |
| Text formatting | Auto-format text based on regex patterns and styles |
| Custom styles | Set colors, fonts, and backgrounds for matched text |
| Suggestion list | Display suggestions when tracking character is typed |
| Message handling | Process messages before sending with `handlePreMessageSend` |

***

## The Formatter Interface

The `CometChatTextFormatter` class provides the foundation for all text formatters in React Native:

```tsx theme={null}
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;
  /** Runs on the RAW message text, before any of the UI Kit's own parsing. Return a string. */
  formatRawText(text: string): string;
  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

```tsx theme={null}
import { CometChatTextFormatter, SuggestionItem } from "@cometchat/chat-uikit-react-native";
```

### 2. Extend it

```tsx theme={null}
class HashTagTextFormatter extends CometChatTextFormatter {
  constructor() {
    super();
    this.setId("hashtag-formatter");
    // A tracking character opens the suggestion list as the user types it. This formatter
    // only styles text, so it tracks nothing — see the Advanced section for suggestions.
    this.setTrackingCharacter("");
  }
}
```

### 3. Match the pattern in `formatRawText`

`formatRawText()` receives the **raw message text as a string**, before any of the UI Kit's own parsing, and returns a string. Rewrite your pattern into markup the UI Kit already draws — here, color and bold:

```tsx theme={null}
class HashTagTextFormatter extends CometChatTextFormatter {
  constructor() {
    super();
    this.setId("hashtag-formatter");
    // No suggestion list for this formatter, so it tracks no character.
    this.setTrackingCharacter("");
  }

  formatRawText(text: string): string {
    // <color=…> is the UI Kit's color markup; ** ** is bold.
    return text.replace(/\B#(\w+)\b/g, "<color=#5dff05>**#$1**</color>");
  }
}
```

<Warning>
  Do **not** put the pattern matching in `getFormattedText()`. That method runs **after** the built-in Markdown formatter, which hands it **JSX** rather than a string — so the usual `if (typeof inputText !== "string") return inputText;` guard returns early and your formatter silently does nothing on any message containing `_`, `**`, `- `, `[` or a backtick. It works only on messages with no Markdown at all, which is why the failure is easy to miss in testing.
</Warning>

***

## Example

A hashtag formatter used with `CometChatMessageList` and `CometChatCompactMessageComposer`.

<CodeGroup>
  ```tsx HashTagTextFormatter.ts theme={null}
  import { CometChatTextFormatter } from "@cometchat/chat-uikit-react-native";

  /** #word — a hashtag, captured without its leading # so we can re-emit it. */
  const HASHTAG_REGEX = /\B#(\w+)\b/g;

  export class HashTagTextFormatter extends CometChatTextFormatter {
    private color = "#5dff05";

    constructor() {
      super();
      this.setId("hashtag-formatter");
      this.setTrackingCharacter("");
    }

    setHashtagColor(color: string) {
      this.color = color;
    }

    /**
     * Reading: your pattern -> markup the UI Kit already renders.
     * Runs on the raw text on every surface, before Markdown.
     */
    formatRawText(text: string): string {
      return text.replace(HASHTAG_REGEX, `<color=${this.color}>**#$1**</color>`);
    }
  }

  export default HashTagTextFormatter;
  ```

  ```tsx ChatScreen.tsx theme={null}
  import React from "react";
  import {
    CometChatCompactMessageComposer,
    CometChatConversations,
    CometChatMessageList,
  } from "@cometchat/chat-uikit-react-native";
  import HashTagTextFormatter from "./HashTagTextFormatter";

  // One instance, shared by every surface that shows the message.
  const hashTagFormatter = new HashTagTextFormatter();

  function ChatScreen({ user, group }: { user?: CometChat.User; group?: CometChat.Group }) {
    return (
      <>
        <CometChatMessageList
          user={user}
          group={group}
          textFormatters={[hashTagFormatter]}
        />
        <CometChatCompactMessageComposer
          user={user}
          group={group}
          textFormatters={[hashTagFormatter]}
        />
      </>
    );
  }

  // The same message also appears in the conversation list — register it there too:
  // <CometChatConversations textFormatters={[hashTagFormatter]} />
  ```
</CodeGroup>

Sending `hello #world **bold** _italic_` now renders `#world` green and bold, with the Markdown around it still formatted.

<Note>
  A formatter only applies where you register it. `CometChatMessageList`, `CometChatConversations`, `CometChatSearch`, `CometChatPinnedMessages`, `CometChatSavedMessages` and `CometChatCompactMessageComposer` each take `textFormatters`. Media captions, the quoted reply inside a bubble, the reply and edit previews, and the message information screen inherit it from the component that renders them.
</Note>

***

## Methods Reference

| Method | Description |
| - | - |
| `setTrackingCharacter(char)` | Character that starts tracking (e.g. `#` for hashtags) |
| `setRegexPatterns(pattern)` | Regex pattern to match text for formatting |
| `formatRawText(text)` | Rewrites the **raw** message text before any UI Kit parsing. Where custom patterns belong |
| `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:

```tsx theme={null}
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

<CardGroup cols={2}>
  <Card title="Custom Text Formatter" href="/ui-kit/react-native/guide-custom-text-formatter">
    Build an app-defined color marker end to end.
  </Card>

  <Card title="Mentions Formatter" href="/ui-kit/react-native/mentions-formatter-guide">
    Add @mentions with styled tokens.
  </Card>

  <Card title="URL Formatter" href="/ui-kit/react-native/url-formatter-guide">
    Auto-detect and style URLs as clickable links.
  </Card>

  <Card title="All Guides" href="/ui-kit/react-native/guide-overview">
    Browse all feature and formatter guides.
  </Card>

  <Card title="Sample App" href="https://github.com/cometchat/cometchat-uikit-react-native/tree/v5/sample">
    Full working sample application on GitHub.
  </Card>
</CardGroup>


This documentation is built and hosted on [Mintlify](https://mintlify.com), a developer documentation platform.