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

# Custom Text Formatter

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

***

## Base Class Overview

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;
  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.setTrackingCharacter("#");
    this.setRegexPatterns(/\B#(\w+)\b/g);
  }
}
```

### 3. Implement formatting methods

Override `getFormattedText` to apply custom styling to matched patterns:

```tsx theme={null}
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](/ui-kit/react-native/message-list) and [CometChatMessageComposer](/ui-kit/react-native/message-composer).

<Tabs>
  <Tab title="HashTagTextFormatter.tsx">
    ```tsx theme={null}
    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;
    ```
  </Tab>

  <Tab title="ChatScreen.tsx">
    ```tsx theme={null}
    import React, { useState, useEffect, useMemo } from "react";
    import { View, SafeAreaView } from "react-native";
    import { CometChat } from "@cometchat/chat-sdk-react-native";
    import {
      CometChatMessageHeader,
      CometChatMessageList,
      CometChatMessageComposer,
    } from "@cometchat/chat-uikit-react-native";
    import HashTagTextFormatter from "./HashTagTextFormatter";

    function ChatScreen(): React.JSX.Element {
      const [chatUser, setChatUser] = useState<CometChat.User | undefined>();

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

      const hashtagFormatter = useMemo(() => new HashTagTextFormatter(), []);

      return (
        <SafeAreaView style={{ flex: 1 }}>
          {chatUser && (
            <View style={{ flex: 1 }}>
              <CometChatMessageHeader user={chatUser} />
              <CometChatMessageList
                user={chatUser}
                textFormatters={[hashtagFormatter]}
              />
              <CometChatMessageComposer
                user={chatUser}
                textFormatters={[hashtagFormatter]}
              />
            </View>
          )}
        </SafeAreaView>
      );
    }

    export default ChatScreen;
    ```
  </Tab>
</Tabs>

***

## Methods Reference

| Method                          | Description                                             |
| ------------------------------- | ------------------------------------------------------- |
| `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:

```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="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>
