AI Integration Quick Reference
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 |
| Related | ShortCut 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.
| 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
TheCometChatTextFormatter 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
OverridegetFormattedText 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.- HashTagTextFormatter.tsx
- ChatScreen.tsx
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;
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;
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 thesearch 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
Mentions Formatter
Add @mentions with styled tokens.
URL Formatter
Auto-detect and style URLs as clickable links.
All Guides
Browse all feature and formatter guides.
Sample App
Full working sample application on GitHub.