### Install Dependencies Source: https://github.com/cometchat/cometchat-uikit-react-native/blob/v5/examples/SampleApp/README.md Install all necessary project dependencies using npm. ```sh npm install ``` -------------------------------- ### Run the Application Source: https://github.com/cometchat/cometchat-uikit-react-native/blob/v5/examples/SampleApp/README.md Start the application on an Android emulator/device or an iOS simulator/device. ```sh npm start npm run android npm run ios ``` -------------------------------- ### Usage Examples Source: https://github.com/cometchat/cometchat-uikit-react-native/blob/v5/_autodocs/api-reference/CometChatGroups.md Provides practical examples of how to implement the CometChatGroups component, including a basic group list setup and a group selection dialog. ```APIDOC ## Usage Examples ### Basic Group List ```typescript import { CometChatGroups } from '@cometchat/chat-uikit-react-native'; export const GroupListScreen = () => { return ( { navigation.navigate('Chat', { group }); }} onError={(error) => { Alert.alert('Error', error.message); }} /> ); }; ``` ### Group Selection Dialog ```typescript const [selectedGroups, setSelectedGroups] = useState([]); { setSelectedGroups(groups); }} onSubmit={(groups) => { // Forward to selected groups forwardMessageToGroups(groups); closeModal(); }} /> ``` ``` -------------------------------- ### Install iOS Dependencies Source: https://github.com/cometchat/cometchat-uikit-react-native/blob/v5/examples/SampleApp/README.md For iOS projects, navigate to the ios directory and install CocoaPods dependencies. ```sh cd ios pod install ``` -------------------------------- ### Custom Event Handling Example Source: https://github.com/cometchat/cometchat-uikit-react-native/blob/v5/_autodocs/api-reference/Events.md Example demonstrating how to attach custom event listeners for messages and group events. ```APIDOC ## Custom Event Handling Example ```typescript import React, { useEffect } from 'react'; import { View, Text } from 'react-native'; import { CometChatUIEventHandler, MessageEvents, CometChatGroupsEvents } from '@cometchat/chat-uikit-react-native'; export const MyCustomComponent = () => { const [messageCount, setMessageCount] = React.useState(0); const [groupCount, setGroupCount] = React.useState(0); useEffect(() => { const listenerId = 'my_component_' + Date.now(); // Create listener const listener = { [MessageEvents.ccMessageAdd]: (message) => { setMessageCount(c => c + 1); console.log('New message:', message.getText()); }, [CometChatGroupsEvents.onGroupCreated]: (group) => { setGroupCount(c => c + 1); console.log('New group:', group.getName()); } }; // Attach listener CometChatUIEventHandler.attachListener(listenerId, listener); // Cleanup on unmount return () => { CometChatUIEventHandler.removeListener(listenerId); }; }, []); return ( Messages: {messageCount} Groups: {groupCount} ); }; ``` ``` -------------------------------- ### Complete Custom Extension Example Source: https://github.com/cometchat/cometchat-uikit-react-native/blob/v5/_autodocs/api-reference/Extensions.md A comprehensive example of a custom CometChat extension, demonstrating how to define its ID, icon, title, lifecycle methods (`enable`, `disable`), data source, and attachment options. ```typescript import React from 'react'; import { View, Text, TouchableOpacity } from 'react-native'; import { ExtensionsDataSource, CometChatMessageComposerAction, DataSource, } from '@cometchat/chat-uikit-react-native'; import { CometChat } from '@cometchat/chat-sdk-react-native'; export class MyCustomExtension extends ExtensionsDataSource { getExtensionId(): string { return 'my_custom_feature'; } getExtensionIcon() { return require('./assets/icon.png'); } getExtensionTitle(): string { return 'Custom Feature'; } enable(): void { console.log('Extension enabled'); } disable(): void { console.log('Extension disabled'); } getDataSource(): DataSource { return {}; } getAttachmentOptions( user?: CometChat.User, group?: CometChat.Group ): CometChatMessageComposerAction[] { return [ { id: 'custom_attachment', title: 'Send Custom', onPress: () => this.sendCustomMessage(user, group), }, ]; } getAuxiliaryOptions(): CometChatMessageComposerAction[] { return []; } private sendCustomMessage( user?: CometChat.User, group?: CometChat.Group ) { const receiverId = user?.getUID() || group?.getGUID(); const receiverType = user ? CometChat.RECEIVER_TYPE.USER : CometChat.RECEIVER_TYPE.GROUP; const customMessage = new CometChat.CustomMessage( receiverId, 'custom_type', { data: 'custom data' }, receiverType ); CometChat.sendMessage(customMessage); } } ``` -------------------------------- ### Initialize CometChatUIKit Once at App Startup Source: https://github.com/cometchat/cometchat-uikit-react-native/blob/v5/_autodocs/README.md Demonstrates the recommended practice of initializing `CometChatUIKit` once when the application starts. This ensures the SDK is ready before any other UI Kit functions are called. ```typescript // app.tsx useEffect(() => { CometChatUIKit.init(settings); }, []); ``` -------------------------------- ### Component Dependencies Example Source: https://github.com/cometchat/cometchat-uikit-react-native/blob/v5/_autodocs/DOCUMENTATION_INDEX.md Illustrates the dependencies and interactions between core CometChat UI components like Conversations, MessageList, and MessageComposer. ```plaintext CometChatConversations ├── uses: CometChatUIKit, CometChatUIEventHandler ├── renders: Conversation items └── communicates: onItemPress, onSelection callbacks CometChatMessageList ├── uses: CometChatUIKit, MessageEvents ├── renders: Message bubbles └── handles: Reactions, Editing, Threading CometChatMessageComposer ├── uses: CometChatUIKit, TextFormatters ├── provides: Attachment options, Mentions └── sends: Text, Media, Custom messages ``` -------------------------------- ### Complete Initialization and Messaging Example Source: https://github.com/cometchat/cometchat-uikit-react-native/blob/v5/_autodocs/api-reference/CometChatUIKit.md Demonstrates the complete initialization process for CometChat UIKit, including logging in a user, sending a text message to a group, and logging out. Ensure you replace placeholder values with your actual app credentials. ```typescript import { CometChatUIKit } from '@cometchat/chat-uikit-react-native'; // 1. Initialize the UI Kit const initSettings = { appId: 'YOUR_APP_ID', region: 'us', authKey: 'YOUR_AUTH_KEY', autoEstablishSocketConnection: true, }; await CometChatUIKit.init(initSettings); // 2. Log in a user const user = await CometChatUIKit.login({ uid: 'user123' }); console.log('User authenticated:', user.getUID()); // 3. Send a message const textMessage = new CometChat.TextMessage( 'group123', 'Hello Group!', CometChat.RECEIVER_TYPE.GROUP ); await CometChatUIKit.sendTextMessage(textMessage); // 4. Log out await CometChatUIKit.logout(); ``` -------------------------------- ### Basic Conversation List Setup Source: https://github.com/cometchat/cometchat-uikit-react-native/blob/v5/_autodocs/api-reference/CometChatConversations.md Initialize the CometChatConversations component for basic display. Includes navigation to a chat screen upon item press and error handling. ```typescript import { CometChatConversations } from '@cometchat/chat-uikit-react-native'; export const ConversationListScreen = () => { return ( { // Navigate to chat screen navigation.navigate('Chat', { conversation }); }} onError={(error) => { console.error('Failed to load conversations:', error.message); }} /> ); }; ``` -------------------------------- ### Initialize CometChat with Production Settings and Auth Source: https://github.com/cometchat/cometchat-uikit-react-native/blob/v5/_autodocs/configuration.md For production, include authentication keys, specify subscription type, and configure push notifications. This example also shows how to log in a user after initialization. ```typescript const settings = { appId: 'YOUR_APP_ID', region: 'eu', authKey: 'YOUR_AUTH_KEY', subscriptionType: 'FRIENDS', autoEstablishSocketConnection: true, deviceToken: 'FCM_TOKEN_FROM_PUSH_SERVICE', }; await CometChatUIKit.init(settings); // Login user const user = await CometChatUIKit.login({ authToken: 'GENERATED_AUTH_TOKEN', }); ``` -------------------------------- ### Basic Message Composer Usage Source: https://github.com/cometchat/cometchat-uikit-react-native/blob/v5/_autodocs/api-reference/CometChatMessageComposer.md A simple example demonstrating how to use the CometChatMessageComposer component in a chat screen. ```APIDOC ## Usage Examples ### Basic Message Composer ```typescript import { CometChatMessageComposer } from '@cometchat/chat-uikit-react-native'; export const ChatScreen = ({ group }) => { return ( { console.log('Message sent:', message.getMessageId()); }} onError={(error) => { Alert.alert('Error', error.message); }} /> ); }; ``` ``` -------------------------------- ### CometChatMessageComposer with Custom Styling Source: https://github.com/cometchat/cometchat-uikit-react-native/blob/v5/_autodocs/api-reference/CometChatMessageComposer.md This example shows how to apply custom styles to the CometChatMessageComposer to match your application's design. ```APIDOC ## CometChatMessageComposer with Custom Styling ### Description Allows for customization of the visual appearance of the message composer. ### Component `CometChatMessageComposer` ### Props - `group` (object): The group object for which the composer is used. - `style` (object): An object containing style properties for different parts of the composer, such as `container` and `inputStyle`. ### Usage Example ```jsx ``` ``` -------------------------------- ### Attach Group Event Listener Example Source: https://github.com/cometchat/cometchat-uikit-react-native/blob/v5/_autodocs/api-reference/Events.md Demonstrates how to attach a listener to handle group events, such as members being added or group information being updated. Requires importing CometChatUIEventHandler and CometChatGroupsEvents. ```typescript import { CometChatGroupsEvents, CometChatUIEventHandler } from '@cometchat/chat-uikit-react-native'; CometChatUIEventHandler.attachListener('group_listener', { [CometChatGroupsEvents.onGroupMemberAdded]: (groupMember) => { console.log('Member added:', groupMember.getName()); }, [CometChatGroupsEvents.onGroupUpdated]: (group) => { console.log('Group updated:', group.getName()); } }); ``` -------------------------------- ### Integrating Search Functionality Source: https://github.com/cometchat/cometchat-uikit-react-native/blob/v5/_autodocs/api-reference/CometChatConversations.md Enable and control the search bar for filtering conversations. This example shows how to manage search text state and handle text changes. ```typescript const [searchText, setSearchText] = useState(''); ( )} /> ``` -------------------------------- ### Basic CometChatMessageComposer Usage Source: https://github.com/cometchat/cometchat-uikit-react-native/blob/v5/_autodocs/api-reference/CometChatMessageComposer.md A basic example of integrating the CometChatMessageComposer into a chat screen. It demonstrates how to pass group information and handle message sending events with `onAfterSendMessage` and error callbacks with `onError`. ```typescript import { CometChatMessageComposer } from '@cometchat/chat-uikit-react-native'; export const ChatScreen = ({ group }) => { return ( { console.log('Message sent:', message.getMessageId()); }} onError={(error) => { Alert.alert('Error', error.message); }} /> ); }; ``` -------------------------------- ### CometChatMessageComposer with Custom Attachments Source: https://github.com/cometchat/cometchat-uikit-react-native/blob/v5/_autodocs/api-reference/CometChatMessageComposer.md This example demonstrates how to configure custom attachment options for the CometChatMessageComposer. Users can tap on these options to trigger specific actions, such as picking a document or sharing their location. ```APIDOC ## CometChatMessageComposer with Custom Attachments ### Description Allows users to attach custom files or share information like documents and location. ### Component `CometChatMessageComposer` ### Props - `group` (object): The group object for which the composer is used. - `attachmentOptions` (function): A function that returns an array of attachment options. Each option is an object with `id`, `title`, and `onPress` properties. ### Usage Example ```jsx [ { id: 'document', title: 'Document', onPress: () => pickDocument(), }, { id: 'location', title: 'Location', onPress: () => shareLocation(), } ]} /> ``` ``` -------------------------------- ### CometChatMessageComposer with Mentions Enabled Source: https://github.com/cometchat/cometchat-uikit-react-native/blob/v5/_autodocs/api-reference/CometChatMessageComposer.md This example demonstrates how to enable and configure mentions within the CometChatMessageComposer. It allows users to tag other group members in messages. ```APIDOC ## CometChatMessageComposer with Mentions Enabled ### Description Enables the functionality for users to mention other group members in their messages. ### Component `CometChatMessageComposer` ### Props - `group` (object): The group object for which the composer is used. - `disableMentions` (boolean): Set to `false` to enable mentions. - `mentionsTargetElement` (string): Specifies the target element for mentions (e.g., 'group_member'). - `onTextChange` (function): A callback function that is triggered when the text in the composer changes, useful for detecting mention patterns. ### Usage Example ```jsx { // Handle text changes for mention detection }} /> ``` ``` -------------------------------- ### Configure User Fetching with UsersRequestBuilder Source: https://github.com/cometchat/cometchat-uikit-react-native/blob/v5/_autodocs/api-reference/CometChatUsers.md Use the usersRequestBuilder prop to customize how user data is fetched. This example sets a limit, specifies the conversation type, and applies a search keyword. ```typescript const requestBuilder = new CometChat.UsersRequestBuilder() .setLimit(50) .withConversationType('user') .setSearchKeyword('john') .build(); ``` -------------------------------- ### Event Flow in CometChat UI Kit Source: https://github.com/cometchat/cometchat-uikit-react-native/blob/v5/_autodocs/README.md Illustrates the typical event flow within the CometChat UI Kit, starting from user actions, through component callbacks and state updates, to event broadcasting and listening by other components. ```plaintext User Action → Component Callback → State Update → Event Broadcast → Other Components Listen ``` -------------------------------- ### Configure Multiple User Selection Source: https://github.com/cometchat/cometchat-uikit-react-native/blob/v5/_autodocs/README.md Sets up the `CometChatUsers` component to allow multiple user selections. The `onSelection` callback updates the state with selected users, and `onSubmit` handles the selected users, for example, for forwarding messages. ```typescript const [selectedUsers, setSelectedUsers] = useState([]); setSelectedUsers(users)} onSubmit={(users) => { // Handle selected users forwardToUsers(users); }} /> ``` -------------------------------- ### Navigate to Sample App Directory Source: https://github.com/cometchat/cometchat-uikit-react-native/blob/v5/examples/SampleAppAI/README.md Change into the specific sample app's directory, such as SampleAppAI. ```sh cd examples/SampleAppAI ``` -------------------------------- ### Navigate to Sample App Directory Source: https://github.com/cometchat/cometchat-uikit-react-native/blob/v5/examples/SampleApp/README.md Change the current directory to the SampleApp within the cloned repository. ```sh cd examples/SampleApp ``` -------------------------------- ### init() Source: https://github.com/cometchat/cometchat-uikit-react-native/blob/v5/_autodocs/api-reference/CometChatUIKit.md Initializes the CometChat UI Kit and the underlying CometChat SDK with provided configuration settings. This is the first step required before using other UIKit functionalities. ```APIDOC ## init() ### Description Initializes the CometChat UI Kit with configuration settings and initializes the underlying CometChat SDK. ### Method `static init(uiKitSettings: UIKitSettings): Promise` ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body - **uiKitSettings** (`UIKitSettings`) - Required - Configuration object for the UI Kit and SDK ### Request Example ```typescript import { CometChatUIKit } from '@cometchat/chat-uikit-react-native'; const settings = { appId: 'YOUR_APP_ID', region: 'us', authKey: 'YOUR_AUTH_KEY', autoEstablishSocketConnection: true, }; await CometChatUIKit.init(settings); ``` ### Response #### Success Response (200) - **void** - Resolves when initialization is complete #### Response Example None (Promise resolves with no value) ### Error Handling Rejects with `CometChat.CometChatException` if initialization fails ``` -------------------------------- ### Initialize with Custom Extensions and Hosts Source: https://github.com/cometchat/cometchat-uikit-react-native/blob/v5/_autodocs/configuration.md Configure CometChat UIKit with custom admin and client hosts, and enable specific extensions like Stickers, Polls, and Link Preview. ```typescript import { StickersExtension, PollsExtension, LinkPreviewExtension, } from '@cometchat/chat-uikit-react-native'; const settings = { appId: 'YOUR_APP_ID', region: 'us', overrideAdminHost: 'https://custom-admin.example.com', overrideClientHost: 'https://custom-client.example.com', extensions: [ new StickersExtension(), new PollsExtension(), new LinkPreviewExtension(), ], }; await CometChatUIKit.init(settings); ``` -------------------------------- ### Get Data Source Source: https://github.com/cometchat/cometchat-uikit-react-native/blob/v5/_autodocs/api-reference/CometChatUIKit.md Retrieves the configured data source instance used for message customization. This method does not require any parameters. ```typescript const dataSource = CometChatUIKit.getDataSource(); ``` -------------------------------- ### Get Conversation Update Settings Source: https://github.com/cometchat/cometchat-uikit-react-native/blob/v5/_autodocs/api-reference/CometChatUIKit.md Retrieves the current conversation update settings configured in the CometChat dashboard. This method does not require any parameters. ```typescript const settings = CometChatUIKit.getConversationUpdateSettings(); ``` -------------------------------- ### Initialize CometChat with Minimal Settings Source: https://github.com/cometchat/cometchat-uikit-react-native/blob/v5/_autodocs/configuration.md Basic initialization requires only the application ID and region. Ensure you import CometChatUIKit before calling init. ```typescript import { CometChatUIKit } from '@cometchat/chat-uikit-react-native'; const settings = { appId: 'YOUR_APP_ID', region: 'us', }; await CometChatUIKit.init(settings); ``` -------------------------------- ### Filtering Users with Custom Request Builder Source: https://github.com/cometchat/cometchat-uikit-react-native/blob/v5/_autodocs/api-reference/CometChatUsers.md Filter the displayed users by providing a custom `usersRequestBuilder`. This example demonstrates filtering for users with the role 'admin'. ```typescript // Custom request builder for filtering const requestBuilder = new CometChat.UsersRequestBuilder() .setLimit(100) .setSearchKeyword('admin') .addCustomData({ role: 'admin' }) .build(); ``` -------------------------------- ### enable() Method Source: https://github.com/cometchat/cometchat-uikit-react-native/blob/v5/_autodocs/api-reference/Extensions.md Called when the extension is activated. Use this method to initialize any necessary resources for the extension. ```typescript enable(): void ``` -------------------------------- ### Append Custom Menu Options to Conversations Source: https://github.com/cometchat/cometchat-uikit-react-native/blob/v5/_autodocs/api-reference/CometChatConversations.md Add custom menu items to the default context menu for conversations. This example adds an 'Archive' option. ```typescript [ { text: 'Archive', onPress: () => archiveConversation(conversation), textColor: '#007AFF' } ]} /> ``` -------------------------------- ### Initialize CometChat with Custom Extension Source: https://github.com/cometchat/cometchat-uikit-react-native/blob/v5/_autodocs/api-reference/Extensions.md Initialize the CometChat SDK, including custom extensions, by passing them in the settings object. ```typescript const myExtension = new MyCustomExtension(); const settings = { appId: 'YOUR_APP_ID', region: 'us', extensions: [ new StickersExtension(), myExtension, // Custom extension new PollsExtension(), ], }; await CometChatUIKit.init(settings); ``` -------------------------------- ### Custom Date Formatting for Conversations Source: https://github.com/cometchat/cometchat-uikit-react-native/blob/v5/_autodocs/api-reference/CometChatConversations.md Implement a custom function to format the date displayed for each conversation. This example shows how to display the time of the last message. ```typescript const datePattern = (conversation: CometChat.Conversation) => { const lastMessageTime = new Date(conversation.getLastMessage().getSentAt() * 1000); return lastMessageTime.toLocaleTimeString(); }; ``` -------------------------------- ### Get Currently Logged-in User Source: https://github.com/cometchat/cometchat-uikit-react-native/blob/v5/_autodocs/api-reference/CometChatUIKit.md Retrieves the CometChat.User object for the user who is currently logged in. This method will reject if no user is logged in or the UI Kit is not initialized. ```typescript const user = await CometChatUIKit.getLoggedInUser(); console.log('Current user:', user.getUID()); ``` -------------------------------- ### Custom Conversations Request Builder Source: https://github.com/cometchat/cometchat-uikit-react-native/blob/v5/_autodocs/api-reference/CometChatConversations.md Customize how conversations are fetched by providing a custom ConversationsRequestBuilder. This example sets a limit of 50 conversations and filters for user-only chats. ```typescript const requestBuilder = new CometChat.ConversationsRequestBuilder() .setLimit(50) .withConversationType('user') .build(); ``` -------------------------------- ### Initialize CometChat UI Kit Source: https://github.com/cometchat/cometchat-uikit-react-native/blob/v5/_autodocs/api-reference/CometChatUIKit.md Initializes the CometChat UI Kit and the underlying SDK with your application's configuration. Ensure you provide your App ID, region, and Auth Key. ```typescript import { CometChatUIKit } from '@cometchat/chat-uikit-react-native'; const settings = { appId: 'YOUR_APP_ID', region: 'us', authKey: 'YOUR_AUTH_KEY', autoEstablishSocketConnection: true, }; await CometChatUIKit.init(settings); ``` -------------------------------- ### Configure Extensions for Loading Source: https://github.com/cometchat/cometchat-uikit-react-native/blob/v5/_autodocs/configuration.md Ensure extensions load correctly by either not setting the `extensions` prop to use defaults or by explicitly including desired extensions. ```typescript // Use default extensions const settings = { appId: 'YOUR_APP_ID', region: 'us', // Don't set extensions prop to use defaults }; // Or explicitly include extensions const settings = { appId: 'YOUR_APP_ID', region: 'us', extensions: [ new StickersExtension(), new PollsExtension(), ], }; ``` -------------------------------- ### Get Current Unix Timestamp in Milliseconds Source: https://github.com/cometchat/cometchat-uikit-react-native/blob/v5/_autodocs/api-reference/CometChatUIKitHelper.md Retrieve the current Unix timestamp in milliseconds using the getUnixTimestampInMilliseconds utility function. This is useful for time-sensitive operations or logging. ```typescript import { getUnixTimestampInMilliseconds } from '@cometchat/chat-uikit-react-native'; const timestamp = getUnixTimestampInMilliseconds(); // Returns: 1717944892345 ``` -------------------------------- ### Initialize CollaborativeWhiteboardExtension Source: https://github.com/cometchat/cometchat-uikit-react-native/blob/v5/_autodocs/api-reference/Extensions.md Instantiate the CollaborativeWhiteboardExtension to enable real-time collaborative drawing features. ```typescript import { CollaborativeWhiteboardExtension } from '@cometchat/chat-uikit-react-native'; const whiteboardExtension = new CollaborativeWhiteboardExtension(); ``` -------------------------------- ### Initialize with Push Notifications Source: https://github.com/cometchat/cometchat-uikit-react-native/blob/v5/_autodocs/configuration.md Initialize CometChat UIKit with push notification support by providing the FCM device token and Google API key. ```typescript import messaging from '@react-native-firebase/messaging'; // Get FCM token const token = await messaging.getToken(); const settings = { appId: 'YOUR_APP_ID', region: 'us', deviceToken: token, googleApiKey: 'YOUR_GOOGLE_API_KEY', }; await CometChatUIKit.init(settings); ``` -------------------------------- ### CometChatMessageComposer with Message Interceptor Source: https://github.com/cometchat/cometchat-uikit-react-native/blob/v5/_autodocs/api-reference/CometChatMessageComposer.md This example shows how to use the `onBeforeSendMessage` prop to intercept and modify messages before they are sent. This is useful for adding custom metadata or performing asynchronous operations. ```APIDOC ## CometChatMessageComposer with Message Interceptor ### Description Intercepts messages before they are sent to allow for modifications like adding metadata or performing asynchronous tasks. ### Component `CometChatMessageComposer` ### Props - `user` (object): The user object for which the composer is used. - `onBeforeSendMessage` (async function): An asynchronous function that receives the message object, allows modifications, and must return the modified message object. ### Usage Example ```jsx { // Add custom metadata const metadata = { version: '1.0', customField: 'value' }; message.setMetadata(metadata); // Simulate processing await new Promise(resolve => setTimeout(resolve, 500)); return message; }} /> ``` ``` -------------------------------- ### Navigate to the Expo Sample App Directory Source: https://github.com/cometchat/cometchat-uikit-react-native/blob/v5/examples/SampleAppExpo/README.md Change into the specific directory for the React Native Expo sample app. ```sh cd examples/SampleAppExpo ``` -------------------------------- ### Custom Conversation Item Rendering Source: https://github.com/cometchat/cometchat-uikit-react-native/blob/v5/_autodocs/api-reference/CometChatConversations.md Completely replace the default conversation item rendering with a custom component. This example demonstrates a simple custom view with the conversation name. ```typescript ( {conversation.getConversationName()} )} onItemPress={(item) => navigation.navigate('Chat', { conversation: item })} /> ``` -------------------------------- ### Initialize with Environment Variables Source: https://github.com/cometchat/cometchat-uikit-react-native/blob/v5/_autodocs/configuration.md Configure CometChat UIKit using environment variables for sensitive credentials like appId, region, and authKey. ```dotenv COMETCHAT_APP_ID=your_app_id COMETCHAT_REGION=us COMETCHAT_AUTH_KEY=your_auth_key ``` ```typescript const settings = { appId: process.env.COMETCHAT_APP_ID, region: process.env.COMETCHAT_REGION, authKey: process.env.COMETCHAT_AUTH_KEY, }; ``` -------------------------------- ### Initialize CallingExtension Source: https://github.com/cometchat/cometchat-uikit-react-native/blob/v5/_autodocs/api-reference/Extensions.md Instantiate the CallingExtension to enable voice and video calling features. ```typescript import { CallingExtension } from '@cometchat/chat-uikit-react-native'; const callingExtension = new CallingExtension(); ``` -------------------------------- ### uiKitSettings Source: https://github.com/cometchat/cometchat-uikit-react-native/blob/v5/_autodocs/api-reference/CometChatUIKit.md Accesses the current UI Kit configuration settings. ```APIDOC ## uiKitSettings ### Description The current UI Kit configuration settings. ### Property Signature `static uiKitSettings: UIKitSettings` ``` -------------------------------- ### Handle Errors During CometChat Operations Source: https://github.com/cometchat/cometchat-uikit-react-native/blob/v5/_autodocs/README.md Provides an example of how to handle potential errors during asynchronous operations like user login. It demonstrates using a try-catch block to gracefully manage failures. ```typescript try { const user = await CometChatUIKit.login({ uid: 'user123' }); } catch (error) { console.error('Login failed:', error.message); showErrorDialog(error.message); } ``` -------------------------------- ### Customize CometChatConversations Component Styles Source: https://github.com/cometchat/cometchat-uikit-react-native/blob/v5/_autodocs/README.md Example of applying custom styles to the `CometChatConversations` component. Styles can be deeply nested to target specific elements like the container, header, and list items. ```typescript ``` -------------------------------- ### Configure CometChat with StickersExtension Source: https://github.com/cometchat/cometchat-uikit-react-native/blob/v5/_autodocs/api-reference/Extensions.md Initialize the CometChat UI Kit with the StickersExtension included in the settings. This makes the sticker functionality available in the chat interface. ```typescript const settings = { appId: 'YOUR_APP_ID', region: 'us', extensions: [new StickersExtension()], }; await CometChatUIKit.init(settings); ``` -------------------------------- ### Initialize CollaborativeDocumentExtension Source: https://github.com/cometchat/cometchat-uikit-react-native/blob/v5/_autodocs/api-reference/Extensions.md Instantiate the CollaborativeDocumentExtension for real-time collaborative document editing. ```typescript import { CollaborativeDocumentExtension } from '@cometchat/chat-uikit-react-native'; const documentExtension = new CollaborativeDocumentExtension(); ``` -------------------------------- ### Initialize StickersExtension Source: https://github.com/cometchat/cometchat-uikit-react-native/blob/v5/_autodocs/api-reference/Extensions.md Instantiate the StickersExtension to enable sticker functionality. This extension allows users to send and receive sticker messages. ```typescript import { StickersExtension } from '@cometchat/chat-uikit-react-native'; const stickerExtension = new StickersExtension(); ``` -------------------------------- ### Configure Subscription Type: ALL_USERS Source: https://github.com/cometchat/cometchat-uikit-react-native/blob/v5/_autodocs/configuration.md Use 'ALL_USERS' to subscribe to all users in real-time. Be mindful of potential high bandwidth usage in large applications. ```typescript const settings = { appId: 'YOUR_APP_ID', region: 'us', subscriptionType: 'ALL_USERS', }; ``` -------------------------------- ### Initialize LinkPreviewExtension Source: https://github.com/cometchat/cometchat-uikit-react-native/blob/v5/_autodocs/api-reference/Extensions.md Instantiate the LinkPreviewExtension to enable automatic URL preview generation. This extension enhances shared links by displaying rich previews. ```typescript import { LinkPreviewExtension } from '@cometchat/chat-uikit-react-native'; const linkPreviewExtension = new LinkPreviewExtension(); ``` -------------------------------- ### Configure CometChat with LinkPreviewExtension Source: https://github.com/cometchat/cometchat-uikit-react-native/blob/v5/_autodocs/api-reference/Extensions.md Initialize the CometChat UI Kit with the LinkPreviewExtension. This enables the automatic extraction and display of link previews for URLs shared in messages. ```typescript const settings = { appId: 'YOUR_APP_ID', region: 'us', extensions: [new LinkPreviewExtension()], }; ``` -------------------------------- ### Group Selection Dialog with Multiple Selection Source: https://github.com/cometchat/cometchat-uikit-react-native/blob/v5/_autodocs/api-reference/CometChatGroups.md This example demonstrates how to use the CometChatGroups component to create a group selection dialog. It enables multiple selection, sets a custom title, hides the default header, and defines callbacks for `onSelection` and `onSubmit`. ```typescript const [selectedGroups, setSelectedGroups] = useState([]); { setSelectedGroups(groups); }} onSubmit={(groups) => { // Forward to selected groups forwardMessageToGroups(groups); closeModal(); }} /> ``` -------------------------------- ### Custom Event Handling with useEffect Source: https://github.com/cometchat/cometchat-uikit-react-native/blob/v5/_autodocs/api-reference/Events.md Example of creating and attaching a custom event listener within a React component using useEffect. It listens for new messages and group creations, updating local state and logging to the console. Ensures the listener is cleaned up on component unmount. ```typescript import React, { useEffect } from 'react'; import { View, Text } from 'react-native'; import { CometChatUIEventHandler, MessageEvents, CometChatGroupsEvents } from '@cometchat/chat-uikit-react-native'; export const MyCustomComponent = () => { const [messageCount, setMessageCount] = React.useState(0); const [groupCount, setGroupCount] = React.useState(0); useEffect(() => { const listenerId = 'my_component_' + Date.now(); // Create listener const listener = { [MessageEvents.ccMessageAdd]: (message) => { setMessageCount(c => c + 1); console.log('New message:', message.getText()); }, [CometChatGroupsEvents.onGroupCreated]: (group) => { setGroupCount(c => c + 1); console.log('New group:', group.getName()); } }; // Attach listener CometChatUIEventHandler.attachListener(listenerId, listener); // Cleanup on unmount return () => { CometChatUIEventHandler.removeListener(listenerId); }; }, []); return ( Messages: {messageCount} Groups: {groupCount} ); }; ``` -------------------------------- ### checkAuthSettings() Source: https://github.com/cometchat/cometchat-uikit-react-native/blob/v5/_autodocs/api-reference/CometChatUIKit.md Validates that the UI Kit is properly initialized with authentication settings. It checks for the presence of UIKitSettings and ensures that the appId is not missing or empty. ```APIDOC ## checkAuthSettings() ### Description Validates that the UI Kit is properly initialized with authentication settings. It checks for the presence of `UIKitSettings` and ensures that the `appId` is not missing or empty. ### Method Signature `static checkAuthSettings(onError: (e: CometChat.CometChatException) => void): boolean` ### Parameters #### Callback - **onError** (Function) - Required - Callback invoked with error details if validation fails. ### Returns - `boolean` — `true` if validation fails, `false` if settings are valid. ### Errors Detected - `UIKitSettings` is null - `appId` is missing or empty ### Example ```typescript CometChatUIKit.checkAuthSettings((error) => { console.error('Auth settings error:', error.message); }); ``` ``` -------------------------------- ### Enable Extensions at Init Time Source: https://github.com/cometchat/cometchat-uikit-react-native/blob/v5/_autodocs/api-reference/Extensions.md Specify which extensions to enable during CometChat SDK initialization by including them in the `extensions` array. ```typescript // At init time - specify which extensions to enable const settings = { appId: 'YOUR_APP_ID', region: 'us', extensions: [ new StickersExtension(), // Enabled new PollsExtension(), // Enabled // CollaborativeWhiteboardExtension not included - disabled ], }; await CometChatUIKit.init(settings); ``` -------------------------------- ### Basic User List Initialization Source: https://github.com/cometchat/cometchat-uikit-react-native/blob/v5/_autodocs/api-reference/CometChatUsers.md Initialize the CometChatUsers component to display a basic user list. Configure event handlers like onItemPress for user selection and onError for handling fetch failures. ```typescript import { CometChatUsers } from '@cometchat/chat-uikit-react-native'; export const UserDirectoryScreen = () => { return ( { // Open chat with user navigation.navigate('Chat', { user }); }} onError={(error) => { Alert.alert('Error', error.message); }} /> ); }; ``` -------------------------------- ### Ensure User Login After Initialization Source: https://github.com/cometchat/cometchat-uikit-react-native/blob/v5/_autodocs/configuration.md Log in a user after successfully initializing CometChatUIKit to ensure proper access to UIKit functions. ```typescript // Ensure login happens after init await CometChatUIKit.init(settings); const user = await CometChatUIKit.login({ uid: 'user123' }); ``` -------------------------------- ### Basic User List Usage Source: https://github.com/cometchat/cometchat-uikit-react-native/blob/v5/_autodocs/api-reference/CometChatUsers.md Demonstrates the basic usage of the CometChatUsers component to display a list of users and handle item presses and errors. ```APIDOC ## Basic User List ```typescript import { CometChatUsers } from '@cometchat/chat-uikit-react-native'; export const UserDirectoryScreen = () => { return ( { // Open chat with user navigation.navigate('Chat', { user }); }} onError={(error) => { Alert.alert('Error', error.message); }} /> ); }; ``` ``` -------------------------------- ### Best Practice: Keep Extensions Lightweight Source: https://github.com/cometchat/cometchat-uikit-react-native/blob/v5/_autodocs/api-reference/Extensions.md Ensures extensions remain performant by performing minimal initialization in the `enable` method. Avoid heavy asynchronous operations during initialization. ```typescript // Good: Minimal initialization enable(): void { this.initializeResources(); } // Avoid: Heavy async operations async enable(): Promise { await downloadLargeDataset(); } ``` -------------------------------- ### Clone the Repository Source: https://github.com/cometchat/cometchat-uikit-react-native/blob/v5/examples/SampleApp/README.md Clone the CometChat React Native UI Kit repository to your local machine. ```sh git clone https://github.com/cometchat/cometchat-uikit-react-native.git ``` -------------------------------- ### Initialize ThumbnailGenerationExtension Source: https://github.com/cometchat/cometchat-uikit-react-native/blob/v5/_autodocs/api-reference/Extensions.md Instantiate the ThumbnailGenerationExtension to automatically generate thumbnails for media messages. ```typescript import { ThumbnailGenerationExtension } from '@cometchat/chat-uikit-react-native'; const thumbnailExtension = new ThumbnailGenerationExtension(); ``` -------------------------------- ### Text Formatting and Menu Options Source: https://github.com/cometchat/cometchat-uikit-react-native/blob/v5/_autodocs/api-reference/CometChatConversations.md Customize text appearance in subtitles and manage context menu options. ```APIDOC ## textFormatters ### Description Array of text formatters to apply to subtitle (message preview). ### Type `Array` ## options ### Description Function that returns menu items to **replace** default context menu options. ### Type `(conversation: CometChat.Conversation) => MenuItemInterface[]` ## addOptions ### Description Function that returns menu items to **append** to default context menu options. ### Type `(conversation: CometChat.Conversation) => MenuItemInterface[]` ### Example ```typescript [ { text: 'Archive', onPress: () => archiveConversation(conversation), textColor: '#007AFF' } ]} /> ``` ``` -------------------------------- ### defaultExtensions Source: https://github.com/cometchat/cometchat-uikit-react-native/blob/v5/_autodocs/api-reference/CometChatUIKit.md An array listing the default extensions that are automatically enabled within the UI Kit. ```APIDOC ## defaultExtensions ### Description Array of default extensions that are automatically enabled. ### Property Signature `static defaultExtensions: ExtensionsDataSource[]` ### Included Extensions - `StickersExtension` - `CollaborativeWhiteboardExtension` - `CollaborativeDocumentExtension` - `MessageTranslationExtension` - `ThumbnailGenerationExtension` - `LinkPreviewExtension` - `PollsExtension` ``` -------------------------------- ### Initialize CometChat UI Kit with Push Notifications Source: https://github.com/cometchat/cometchat-uikit-react-native/blob/v5/_autodocs/configuration.md Initialize the CometChat UI Kit with your application credentials and FCM token for push notifications. Ensure environment variables for appId, region, and authKey are set. ```typescript import { CometChatUIKit } from '@cometchat/chat-uikit-react-native'; import messaging from '@react-native-firebase/messaging'; export class CometChatService { static async initialize() { try { // Get push notification token const fcmToken = await messaging.getToken(); // Configure UI Kit const settings = { appId: process.env.COMETCHAT_APP_ID, region: process.env.COMETCHAT_REGION, authKey: process.env.COMETCHAT_AUTH_KEY, subscriptionType: 'FRIENDS', autoEstablishSocketConnection: true, deviceToken: fcmToken, }; // Initialize await CometChatUIKit.init(settings); console.log('CometChat UIKit initialized'); return true; } catch (error) { console.error('CometChat initialization failed:', error); return false; } } static async login(uid: string) { try { const user = await CometChatUIKit.login({ uid }); console.log('User logged in:', user.getUID()); return user; } catch (error) { console.error('Login failed:', error); throw error; } } static async logout() { try { await CometChatUIKit.logout(); console.log('User logged out'); } catch (error) { console.error('Logout failed:', error); throw error; } } } // In your app's main entry point App.tsx: useEffect(() => { CometChatService.initialize(); }, []); ``` -------------------------------- ### Handle Initialization Errors Source: https://github.com/cometchat/cometchat-uikit-react-native/blob/v5/_autodocs/configuration.md Implement error handling for CometChatUIKit initialization to catch and log potential issues. ```typescript try { await CometChatUIKit.init(settings); } catch (error) { console.error('Init failed:', error); } ``` -------------------------------- ### Check Authentication Settings Source: https://github.com/cometchat/cometchat-uikit-react-native/blob/v5/_autodocs/api-reference/CometChatUIKit.md Validates that the UI Kit is properly initialized with authentication settings. Call this to ensure your app ID and auth key are correctly configured before proceeding. ```typescript CometChatUIKit.checkAuthSettings((error) => { console.error('Auth settings error:', error.message); }); ``` -------------------------------- ### Basic Custom Extension Template Source: https://github.com/cometchat/cometchat-uikit-react-native/blob/v5/_autodocs/api-reference/Extensions.md A template for creating a custom CometChat extension, including methods for enabling, disabling, and defining extension behavior. ```typescript import { ExtensionsDataSource, CometChatMessageComposerAction, DataSource, } from '@cometchat/chat-uikit-react-native'; import { CometChat } from '@cometchat/chat-sdk-react-native'; import { Image, ImageSourcePropType } from 'react-native'; export class MyCustomExtension extends ExtensionsDataSource { getExtensionId(): string { return 'my_extension'; } getExtensionIcon(): ImageSourcePropType | JSX.Element { return require('./assets/icon.png'); } getExtensionTitle(): string { return 'My Extension'; } enable(): void { console.log('My extension enabled'); // Initialize resources } disable(): void { console.log('My extension disabled'); // Clean up resources } getDataSource(): DataSource { return { getMessageTemplate: () => null, // Optional getOptions: () => [], // Optional }; } getAttachmentOptions( user?: CometChat.User, group?: CometChat.Group ): CometChatMessageComposerAction[] { return [ { id: 'my_action', title: 'My Action', icon: this.getExtensionIcon(), onPress: () => this.handleAction(user, group), }, ]; } getAuxiliaryOptions( user?: CometChat.User, group?: CometChat.Group ): CometChatMessageComposerAction[] { return []; // Optional } private handleAction(user?: CometChat.User, group?: CometChat.Group) { // Handle action console.log('Action triggered'); } } ``` -------------------------------- ### Best Practice: Handle Errors Gracefully Source: https://github.com/cometchat/cometchat-uikit-react-native/blob/v5/_autodocs/api-reference/Extensions.md Implement robust error handling within the `enable` method using try-catch blocks to log errors and provide fallback behavior if initialization fails. ```typescript enable(): void { try { // Initialize } catch (error) { console.error('Extension init failed:', error); // Provide fallback behavior } } ``` -------------------------------- ### Initialize PollsExtension Source: https://github.com/cometchat/cometchat-uikit-react-native/blob/v5/_autodocs/api-reference/Extensions.md Instantiate the PollsExtension to enable poll creation and voting. This extension allows users to create and participate in polls within chats. ```typescript import { PollsExtension } from '@cometchat/chat-uikit-react-native'; const pollsExtension = new PollsExtension(); ``` -------------------------------- ### Message Actions and Options Source: https://github.com/cometchat/cometchat-uikit-react-native/blob/v5/_autodocs/api-reference/CometChatMessageList.md Configure and customize the actions available for messages, such as replying, deleting, editing, and reacting. ```APIDOC ## messageActions ### Description Function returning custom message action options. ### Type `(message: CometChat.BaseMessage) => CometChatMessageComposerAction[]` ``` ```APIDOC ## addOptions ### Description Function to append additional message options. ### Type `(message: CometChat.BaseMessage) => CometChatMessageComposerAction[]` ``` ```APIDOC ## hideMessageInfo ### Description Hide the message info (delivery status, reactions count). ### Type `boolean` ### Default `false` ``` ```APIDOC ## hideDeleteMessageOption ### Description Hide delete message option. ### Type `boolean` ### Default `false` ``` ```APIDOC ## hideEditMessageOption ### Description Hide edit message option. ### Type `boolean` ### Default `false` ``` ```APIDOC ## hideReplyOption ### Description Hide reply option. ### Type `boolean` ### Default `false` ``` ```APIDOC ## hideReplyInThreadOption ### Description Hide reply in thread option. ### Type `boolean` ### Default `false` ``` ```APIDOC ## hideReactionOption ### Description Hide reaction option. ### Type `boolean` ### Default `false` ``` ```APIDOC ## hideShareMessageOption ### Description Hide share message option. ### Type `boolean` ### Default `false` ``` ```APIDOC ## disableEditMessage ### Description Disable message editing functionality. ### Type `boolean` ### Default `false` ``` ```APIDOC ## disableDeleteMessage ### Description Disable message deletion functionality. ### Type `boolean` ### Default `false` ``` ```APIDOC ## disableShareMessage ### Description Disable message sharing functionality. ### Type `boolean` ### Default `false` ``` ```APIDOC ## disableReplyInThread ### Description Disable reply in thread functionality. ### Type `boolean` ### Default `false` ``` ```APIDOC ## disableReply ### Description Disable reply functionality entirely. ### Type `boolean` ### Default `false` ``` -------------------------------- ### CometChatMediaRecorderInterface Source: https://github.com/cometchat/cometchat-uikit-react-native/blob/v5/_autodocs/types.md Props for the media recorder component, including various callback functions. ```APIDOC ## CometChatMediaRecorderInterface ### Description Props for the media recorder component. ### Fields - **onStart** (optional) - Callback when recording starts. - **onStop** (optional) - Callback when recording stops, returning the recorded file path. - **onPause** (optional) - Callback when recording is paused. - **onPlay** (optional) - Callback when recording is played. - **onSend** (optional) - Callback when the recorded file is sent, returning the recorded file path. - **onClose** (optional) - Callback when the recorder is closed. - **style** (optional) - DeepPartial - Custom styling for the media recorder. ``` -------------------------------- ### Custom Rendering Components Source: https://github.com/cometchat/cometchat-uikit-react-native/blob/v5/_autodocs/api-reference/CometChatConversations.md Replace default UI elements with custom components for a personalized user experience. ```APIDOC ## ItemView ### Description Completely replaces the default conversation item rendering. When provided, all internal views (LeadingView, TitleView, etc.) are ignored. You must handle selection, item press, and long press yourself. **Note:** Use `ItemView` only if you need complete custom rendering. ### Type `(item: CometChat.Conversation) => JSX.Element` ### Example ```typescript ( {conversation.getConversationName()} )} onItemPress={(item) => navigation.navigate('Chat', { conversation: item })} /> ``` ## LeadingView ### Description Custom component for the left side (usually avatar). ### Type `(conversation: CometChat.Conversation) => JSX.Element` ## TitleView ### Description Custom component for the conversation title/name. ### Type `(conversation: CometChat.Conversation) => JSX.Element` ## SubtitleView ### Description Custom component for the subtitle (last message preview). ### Type `(item: CometChat.Conversation) => JSX.Element` ## TrailingView ### Description Custom component for the right side (usually timestamp and badge). ### Type `(item: CometChat.Conversation) => JSX.Element` ## AppBarOptions ### Description Custom component for header/app bar action buttons. ### Type `() => JSX.Element` ## SearchView ### Description Custom search input component. ### Type `() => JSX.Element` ``` -------------------------------- ### Display a Basic Chat Screen Source: https://github.com/cometchat/cometchat-uikit-react-native/blob/v5/_autodocs/README.md Renders a chat interface by combining the message list and message composer components. Ensure the `group` prop is correctly passed. ```typescript const ChatScreen = ({ group }) => { return ( ); }; ``` -------------------------------- ### CometChatAudioBubbleInterface Source: https://github.com/cometchat/cometchat-uikit-react-native/blob/v5/_autodocs/types.md Props for the audio message bubble component. ```APIDOC ## CometChatAudioBubbleInterface ### Description Props for audio message bubble. ### Fields - **message** (CometChat.MediaMessage) - The media message object (audio) to display. - **style** (optional) - DeepPartial - Custom styling for the audio bubble. - **onPress** (optional) - Callback function when the audio bubble is pressed. - **onLongPress** (optional) - Callback function when the audio bubble is long-pressed. ``` -------------------------------- ### Use Environment Variables for Credentials Source: https://github.com/cometchat/cometchat-uikit-react-native/blob/v5/_autodocs/configuration.md Security best practice: Use environment variables to securely manage sensitive configuration values like appId and authKey. ```typescript // DO THIS const settings = { appId: process.env.COMETCHAT_APP_ID, authKey: process.env.COMETCHAT_AUTH_KEY, }; ```