diff --git a/.gitignore b/.gitignore index 96adadbc8..febf5f018 100644 --- a/.gitignore +++ b/.gitignore @@ -1,3 +1,4 @@ .DS_Store .kiro/ +/cometchat-uikit-react-6 diff --git a/docs.json b/docs.json index 9b489faf5..5ff55b78a 100644 --- a/docs.json +++ b/docs.json @@ -549,6 +549,7 @@ "ui-kit/react/property-changes" ] }, + "ui-kit/react/troubleshooting", "ui-kit/react/link/sample", "ui-kit/react/link/changelog", "ui-kit/react/link/figma" diff --git a/fundamentals/extensions-overview.mdx b/fundamentals/extensions-overview.mdx index d6e58d1dd..3aa338a73 100644 --- a/fundamentals/extensions-overview.mdx +++ b/fundamentals/extensions-overview.mdx @@ -11,32 +11,32 @@ Extensions pickup where our core leaves. They help extend the functionality of C Extensions that help improve the user messaging experience. *Recommended for most apps.* -[Pin message](/fundamentals/pin-message)\ [Bitly](/fundamentals/bitly)\ -[Avatars](/fundamentals/avatars)\ -[Message shortcuts](/fundamentals/message-shortcuts)\ [Link Preview](/fundamentals/link-preview)\ +[Message shortcuts](/fundamentals/message-shortcuts)\ +[Pin message](/fundamentals/pin-message)\ [Rich Media Preview](/fundamentals/rich-media-preview)\ [Save message](/fundamentals/save-message)\ [Thumbnail Generation](/fundamentals/thumbnail-generation)\ [TinyURL](/fundamentals/tinyurl)\ -[Voice Transcription](/fundamentals/voice-transcription) +[Voice Transcription](/fundamentals/voice-transcription)\ +[Avatars](/fundamentals/avatars) ### User Engagement Extensions that help increase user engagement. *Recommended for advanced apps.* -[Email replies](/fundamentals/email-replies)\ -[Polls](/fundamentals/polls)\ [Giphy](/fundamentals/giphy)\ -[Mentions](/fundamentals/mentions)\ [Message Translation](/fundamentals/message-translation)\ -[Reactions](/fundamentals/reactions)\ -[Smart Reply](/fundamentals/smart-replies)\ +[Polls](/fundamentals/polls)\ +[Reminders](/fundamentals/reminders)\ [Stickers](/fundamentals/stickers)\ [Stipop](/fundamentals/stickers-stipop)\ [Tenor](/fundamentals/tenor)\ -[Reminders](/fundamentals/reminders)\ +[Email replies](/fundamentals/email-replies)\ +[Mentions](/fundamentals/mentions)\ +[Reactions](/fundamentals/reactions)\ +[Smart Reply](/fundamentals/smart-replies)\ [Live Streaming by api.video](/fundamentals/video-broadcasting) ### Collaboration @@ -46,12 +46,19 @@ Extensions that help with collaboration. *Recommended for advanced apps.* [Collaborative Whiteboard](/fundamentals/collaborative-whiteboard)\ [Collaborative Document](/fundamentals/collaborative-document) +### Security + +*Extensions that help you to build adding extra security to your apps.* *Recommended for live streaming and event apps.* + +[Disappearing messages](/fundamentals/disappearing-messages)\ +[End to End Encryption](/fundamentals/end-to-end-encryption) + ### Customer Support Extensions that help you add support to your app. *Recommended for advanced apps.* -[Intercom](/fundamentals/intercom)\ -[Chatwoot](/fundamentals/chatwoot) +[Chatwoot](/fundamentals/chatwoot)\ +[Intercom](/fundamentals/intercom) ### Notifications @@ -66,10 +73,3 @@ Extensions that help alert users of new messages. *Recommended for all apps.* *Extensions that help you to build a safe messaging environment.* *Recommended for live streaming and event apps.* [Legacy Moderation Extensions](/moderation/legacy-extensions) - -### Security - -*Extensions that help you to build adding extra security to your apps.* *Recommended for live streaming and event apps.* - -[Disappearing messages](/fundamentals/disappearing-messages)\ -[End to End Encryption](/fundamentals/end-to-end-encryption) diff --git a/sdk/javascript/video-view-customisation.mdx b/sdk/javascript/video-view-customisation.mdx index 2fd632577..5e3880224 100644 --- a/sdk/javascript/video-view-customisation.mdx +++ b/sdk/javascript/video-view-customisation.mdx @@ -1,8 +1,16 @@ --- title: "Video View Customisation" +description: "Customize the main video container in CometChat calls — aspect ratio, full screen button, name label, and network label positioning." --- - + +**Quick Reference** +- **Class:** `CometChat.MainVideoContainerSetting` +- **Apply via:** `CallSettingsBuilder.setMainVideoContainerSetting(videoSettings)` +- **Customizable elements:** Aspect ratio, full screen button, name label, network label +- **Position constants:** `POSITION_TOP_LEFT`, `POSITION_TOP_RIGHT`, `POSITION_BOTTOM_LEFT`, `POSITION_BOTTOM_RIGHT` +- **Requires:** [Default Calling](/sdk/javascript/default-call) or [Direct Calling](/sdk/javascript/direct-call) setup + This section will guide you to customise the main video container. @@ -26,16 +34,62 @@ The `MainVideoContainerSetting` Class is the required in case you want to custom Example: - -```typescript + +```javascript let videoSettings = new CometChat.MainVideoContainerSetting(); -videoSettings.setMainVideoAspectRatio(CometChat.CallSettings.ASPECT_RATIO_CONTAIN); +videoSettings.setMainVideoAspectRatio(CometChat.CallSettings.ASPECT_RATIO_CONTAIN); videoSettings.setFullScreenButtonParams(CometChat.CallSettings.POSITION_BOTTOM_RIGHT, true); videoSettings.setNameLabelParams(CometChat.CallSettings.POSITION_BOTTOM_LEFT, true, "rgba(27, 27, 27, 0.4)"); -videoSettings.setNetworkLabelParams(CometChat.CallSettings.POSITION_BOTTOM_RIGHT, true); +videoSettings.setNetworkLabelParams(CometChat.CallSettings.POSITION_BOTTOM_RIGHT, true); ``` - + +```typescript +let videoSettings: CometChat.MainVideoContainerSetting = new CometChat.MainVideoContainerSetting(); +videoSettings.setMainVideoAspectRatio(CometChat.CallSettings.ASPECT_RATIO_CONTAIN); +videoSettings.setFullScreenButtonParams(CometChat.CallSettings.POSITION_BOTTOM_RIGHT, true); +videoSettings.setNameLabelParams(CometChat.CallSettings.POSITION_BOTTOM_LEFT, true, "rgba(27, 27, 27, 0.4)"); +videoSettings.setNetworkLabelParams(CometChat.CallSettings.POSITION_BOTTOM_RIGHT, true); +``` + + + + + +| Practice | Details | +| --- | --- | +| Aspect ratio choice | Use `ASPECT_RATIO_CONTAIN` to show the full video without cropping; use `ASPECT_RATIO_COVER` for a full-bleed look that may crop edges | +| Label positioning | Avoid placing the name label and network label in the same corner to prevent overlap | +| Full screen button | Keep the full screen button visible for better UX; only hide it if your app provides its own full screen toggle | + + + + +| Symptom | Cause | Fix | +| --- | --- | --- | +| Video settings not applied | `setMainVideoContainerSetting()` not called on `CallSettingsBuilder` | Pass the `MainVideoContainerSetting` object to `CallSettingsBuilder.setMainVideoContainerSetting()` before calling `startCall()` | +| Labels overlapping | Multiple labels positioned in the same corner | Assign different position constants to each label | +| Full screen button missing | Visibility set to `false` | Set the second parameter of `setFullScreenButtonParams()` to `true` | + + + + +## Next Steps + + + + Implement default audio/video calling. + + + Implement direct calling without call events. + + + Add virtual background and blur effects. + + + Record calls for playback. + + diff --git a/sdk/javascript/virtual-background.mdx b/sdk/javascript/virtual-background.mdx index 63edd0a83..0879041c1 100644 --- a/sdk/javascript/virtual-background.mdx +++ b/sdk/javascript/virtual-background.mdx @@ -1,8 +1,16 @@ --- title: "Virtual Background" +description: "Implement virtual background features in CometChat video calls — background blur, custom images, and enforced backgrounds using the JavaScript SDK." --- - + +**Quick Reference** +- **Settings class:** `CometChat.VirtualBackground` +- **Apply via:** `CallSettingsBuilder.setVirtualBackground(virtualBackground)` +- **Toggle UI:** `CallSettingsBuilder.showVirtualBackgroundSetting(true|false)` +- **Runtime control:** `CometChat.CallController.getInstance()` → `setBackgroundBlur()`, `setBackgroundImage()`, `openVirtualBackground()` +- **Requires:** [Default Calling](/sdk/javascript/default-call) or [Direct Calling](/sdk/javascript/direct-call) setup + This section will guide you to implement virtual background feature in video calls. @@ -35,21 +43,17 @@ You can use the `openVirtualBackground()` method to open the virtual background -```js +```javascript let callController = CometChat.CallController.getInstance(); callController.openVirtualBackground(); ``` - - ```typescript let callController: CometChat.CallController = CometChat.CallController.getInstance(); callController.openVirtualBackground(); ``` - - ### Set Background Blur @@ -58,23 +62,19 @@ You can use the `setBackgroundBlur()` method to apply background blur on the vid -```js +```javascript let callController = CometChat.CallController.getInstance(); let blurLevel = 1; callController.setBackgroundBlur(blurLevel); ``` - - ```typescript let callController: CometChat.CallController = CometChat.CallController.getInstance(); let blurLevel: number = 1; callController.setBackgroundBlur(blurLevel); ``` - - ### Set Background Image @@ -83,23 +83,19 @@ You can use the `setBackgroundImage()`method to set the background image. This m -```js +```javascript let callController = CometChat.CallController.getInstance(); let imageURL = "URL_OF_BACKGROUND_IMAGE"; callController.setBackgroundImage(imageURL); ``` - - ```typescript let callController: CometChat.CallController = CometChat.CallController.getInstance(); let imageURL: string = "URL_OF_BACKGROUND_IMAGE"; callController.setBackgroundImage(imageURL); ``` - - ## Virtual Background Settings @@ -114,3 +110,44 @@ The `VirtualBackground` Class is the required in case you want to change how the | `setImages(images: Array)` | This method allows developer to add their custom background image which the end user can choose. | | `enforceBackgroundBlur(enforceBackgroundBlur: number)` | This method starts the call with background blurred. To blur the background you need to pass an integer value between 1-99 which decides the blur level. **Default = 0** | | `enforceBackgroundImage(enforceBackgroundImage: string)` | This methods starts the call with the provided background image. | + + + + +| Practice | Details | +| --- | --- | +| Blur level range | Use values between 1-99 for `enforceBackgroundBlur()`. Higher values produce stronger blur. A value of 0 disables blur | +| Image hosting | Host background images on a CDN for fast loading. Large images may cause lag when applied | +| Enforce vs allow | Use `enforceBackgroundBlur()` or `enforceBackgroundImage()` when you want a mandatory background (e.g., for privacy). Use `allowBackgroundBlur()` and `allowUserImages()` to let users choose | +| Custom buttons | Use `CallController` methods (`setBackgroundBlur`, `setBackgroundImage`, `openVirtualBackground`) when building a custom UI instead of the default CometChat menu | + + + + +| Symptom | Cause | Fix | +| --- | --- | --- | +| Virtual background option not visible | `showVirtualBackgroundSetting(false)` was set | Set `showVirtualBackgroundSetting(true)` in `CallSettingsBuilder` | +| Background blur not applied on call start | `enforceBackgroundBlur()` not set or set to 0 | Pass a value between 1-99 to `enforceBackgroundBlur()` | +| Custom images not appearing | `setImages()` not called or empty array passed | Pass a non-empty array of valid image URLs to `setImages()` | +| `CallController.getInstance()` returns null | Called before the call has started | Only use `CallController` methods after `startCall()` has been invoked | +| User can't upload their own images | `allowUserImages(false)` was set | Set `allowUserImages(true)` in the `VirtualBackground` configuration | + + + + +## Next Steps + + + + Customize the main video container layout. + + + Record calls for playback. + + + Enable screen sharing and presenter mode. + + + Customize the calling UI appearance. + + diff --git a/ui-kit/react/ai-assistant-chat.mdx b/ui-kit/react/ai-assistant-chat.mdx index 2cf33676c..343751240 100644 --- a/ui-kit/react/ai-assistant-chat.mdx +++ b/ui-kit/react/ai-assistant-chat.mdx @@ -1,938 +1,961 @@ --- title: "AI Assistant Chat" +description: "Composite AI agent chat with streaming responses, quick suggestions, new-chat reset, and chat history sidebar." --- + +```json +{ + "component": "CometChatAIAssistantChat", + "package": "@cometchat/chat-uikit-react", + "import": "import { CometChatAIAssistantChat } from \"@cometchat/chat-uikit-react\";", + "description": "Composite AI agent chat with streaming responses, quick suggestions, new-chat reset, and chat history sidebar.", + "cssRootClass": ".cometchat-ai-assistant-chat", + "requiredProps": { + "user": "CometChat.User — the AI agent user object" + }, + "optionalProps": { + "streamingSpeed": "number", + "suggestedMessages": "string[]", + "hideSuggestedMessages": "boolean", + "hideNewChat": "boolean", + "hideChatHistory": "boolean", + "showBackButton": "boolean", + "showCloseButton": "boolean", + "loadLastAgentConversation": "boolean", + "parentMessageId": "number", + "aiAssistantTools": "CometChatAIAssistantTools", + "templates": "CometChatMessageTemplate[]", + "headerItemView": "JSX.Element", + "headerTitleView": "JSX.Element", + "headerSubtitleView": "JSX.Element", + "headerLeadingView": "JSX.Element", + "headerTrailingView": "JSX.Element", + "headerAuxiliaryButtonView": "JSX.Element", + "emptyChatImageView": "JSX.Element", + "emptyChatGreetingView": "JSX.Element", + "emptyChatIntroMessageView": "JSX.Element", + "emptyView": "JSX.Element", + "loadingView": "JSX.Element", + "errorView": "JSX.Element" + }, + "callbacks": { + "onBackButtonClicked": "() => void", + "onCloseButtonClicked": "() => void", + "onSendButtonClick": "(message: CometChat.BaseMessage, previewMessageMode?: PreviewMessageMode) => void", + "onError": "(e: CometChat.CometChatException) => void" + }, + "events": null, + "minimalExample": "" +} +``` + -## Overview - -`CometChatAIAssistantChat` is a composite component that assembles the message header, message list, and message composer to provide an AI agent chat experience. It supports streaming responses, quick starter suggestions, "New Chat" to reset context, and a chat history sidebar. +## Where It Fits - - - +`CometChatAIAssistantChat` is a standalone AI chat panel. It composes an internal message header, message list, and message composer into a self-contained AI conversation experience. It requires a `CometChat.User` representing the AI agent. - - ```tsx -import React from "react"; +import { useState, useEffect } from "react"; import { CometChat } from "@cometchat/chat-sdk-javascript"; import { CometChatAIAssistantChat } from "@cometchat/chat-uikit-react"; -export function AIAssistantChatDemo() { - const [agent, setAgent] = React.useState(); +function AIAssistantPanel() { + const [agent, setAgent] = useState(); - React.useEffect(() => { - // Replace with your assistant UID - CometChat.getUser("assistant_uid").then((u) => setAgent(u)); - }, []); + useEffect(() => { + CometChat.getUser("assistant_uid").then((u) => setAgent(u)); + }, []); - if (!agent) return null; + if (!agent) return null; - return( - <> - - - ); + return ( +
+ +
+ ); } - ``` -
+ + + + +--- + +## Minimal Render - ```tsx -import { AIAssistantChatDemo } from "./AIAssistantChatDemo"; +import { useState, useEffect } from "react"; +import { CometChat } from "@cometchat/chat-sdk-javascript"; +import { CometChatAIAssistantChat } from "@cometchat/chat-uikit-react"; -export default function App() { - return ( -
- -
- ); +function AIAssistantDemo() { + const [agent, setAgent] = useState(); + + useEffect(() => { + CometChat.getUser("assistant_uid").then((u) => setAgent(u)); + }, []); + + if (!agent) return null; + + return ; } ``` -
-
- - - A `CometChat.User` (the AI agent) is required to start the assistant chat. - +Root CSS class: `.cometchat-ai-assistant-chat` --- -## Actions +## Actions and Events -[Actions](/ui-kit/react/components-overview#actions) control how a component behaves. You can hook into the following callbacks: +### Callback Props -##### 1. onBackButtonClicked +#### onBackButtonClicked -Called when the header back button is clicked (visible when `showBackButton` is true). +Fires when the header back button is clicked. Requires `showBackButton={true}`. + +| Detail | Value | +| --- | --- | +| When it fires | User clicks the back button | +| Payload type | `() => void` | - - ```tsx -import React from "react"; +import { useState, useEffect } from "react"; import { CometChat } from "@cometchat/chat-sdk-javascript"; import { CometChatAIAssistantChat } from "@cometchat/chat-uikit-react"; -export function AIAssistantChatDemo() { - const [agent, setAgent] = React.useState(); - - React.useEffect(() => { - CometChat.getUser("assistant_uid").then((u) => setAgent(u)); - }, []); +function AIAssistantWithBack() { + const [agent, setAgent] = useState(); - const handleBack = () => { - // your custom action - }; + useEffect(() => { + CometChat.getUser("assistant_uid").then((u) => setAgent(u)); + }, []); - if (!agent) return null; + if (!agent) return null; - return ( - - ); + return ( + console.log("Back clicked")} + /> + ); } - ``` - +#### onCloseButtonClicked + +Fires when the header close button is clicked. Requires `showCloseButton={true}`. + +| Detail | Value | +| --- | --- | +| When it fires | User clicks the close button | +| Payload type | `() => void` | - -```jsx -import React from "react"; +```tsx +import { useState, useEffect } from "react"; import { CometChat } from "@cometchat/chat-sdk-javascript"; import { CometChatAIAssistantChat } from "@cometchat/chat-uikit-react"; -export function AIAssistantChatDemo() { - const [agent, setAgent] = React.useState(null); - - React.useEffect(() => { - CometChat.getUser("assistant_uid").then((u) => setAgent(u)); - }, []); +function AIAssistantWithClose() { + const [agent, setAgent] = useState(); - const handleBack = () => { - // your custom action - }; + useEffect(() => { + CometChat.getUser("assistant_uid").then((u) => setAgent(u)); + }, []); - if (!agent) return null; + if (!agent) return null; - return ( - - ); + return ( + console.log("Close clicked")} + /> + ); } ``` - - +#### onSendButtonClick -##### 2. onCloseButtonClicked +Fires when the composer send button is clicked. -Called when the header close button is clicked (visible when `showCloseButton` is true). +| Detail | Value | +| --- | --- | +| When it fires | User clicks the send button | +| Payload type | `(message: CometChat.BaseMessage, previewMessageMode?: PreviewMessageMode) => void` | - - ```tsx -import React from "react"; +import { useState, useEffect } from "react"; import { CometChat } from "@cometchat/chat-sdk-javascript"; import { CometChatAIAssistantChat } from "@cometchat/chat-uikit-react"; -export function AIAssistantChatDemo() { - const [agent, setAgent] = React.useState(); - - React.useEffect(() => { - CometChat.getUser("assistant_uid").then((u) => setAgent(u)); - }, []); +function AIAssistantWithSend() { + const [agent, setAgent] = useState(); - const handleClose = () => { - // your custom action - }; + useEffect(() => { + CometChat.getUser("assistant_uid").then((u) => setAgent(u)); + }, []); - if (!agent) return null; + if (!agent) return null; - return ( - - ); + return ( + console.log("Sent:", message)} + /> + ); } ``` - +#### onError + +Fires when the component encounters an internal error. - -```jsx -import React from "react"; +| Detail | Value | +| --- | --- | +| When it fires | Any internal error during rendering or data fetching | +| Payload type | `(error: CometChat.CometChatException) => void` | + +```tsx +import { useState, useEffect } from "react"; import { CometChat } from "@cometchat/chat-sdk-javascript"; import { CometChatAIAssistantChat } from "@cometchat/chat-uikit-react"; -export function AIAssistantChatDemo() { - const [agent, setAgent] = React.useState(null); - - React.useEffect(() => { - CometChat.getUser("assistant_uid").then((u) => setAgent(u)); - }, []); +function AIAssistantWithError() { + const [agent, setAgent] = useState(); - const handleClose = () => { - // your custom action - }; + useEffect(() => { + CometChat.getUser("assistant_uid").then((u) => setAgent(u)); + }, []); - if (!agent) return null; + if (!agent) return null; - return ( - - ); + return ( + console.error("AI chat error:", error)} + /> + ); } ``` - - +### Global UI Events -##### 3. onSendButtonClick +The AI Assistant Chat component does not emit global UI events. Interaction handling uses the callback props above. -Called when the composer send button is clicked. +### SDK Events (Real-Time, Automatic) + +The component internally manages SDK communication for AI streaming. No manual listener attachment needed. + +--- + +## Custom View Slots + +| Slot | Type | Replaces | +| --- | --- | --- | +| `headerItemView` | `JSX.Element` | Entire header list item | +| `headerTitleView` | `JSX.Element` | Header title text | +| `headerSubtitleView` | `JSX.Element` | Header subtitle text | +| `headerLeadingView` | `JSX.Element` | Header avatar / left section | +| `headerTrailingView` | `JSX.Element` | Header right section | +| `headerAuxiliaryButtonView` | `JSX.Element` | Header auxiliary buttons (New Chat, History) | +| `emptyChatImageView` | `JSX.Element` | Empty state image | +| `emptyChatGreetingView` | `JSX.Element` | Empty state greeting title | +| `emptyChatIntroMessageView` | `JSX.Element` | Empty state intro subtitle | +| `emptyView` | `JSX.Element` | Message list empty state | +| `loadingView` | `JSX.Element` | Loading state | +| `errorView` | `JSX.Element` | Error state | +| `aiAssistantTools` | `CometChatAIAssistantTools` | Tool/function call handlers | +| `templates` | `CometChatMessageTemplate[]` | Message bubble templates | + +### emptyChatImageView + + + + - - ```tsx -import React from "react"; +import { useState, useEffect } from "react"; import { CometChat } from "@cometchat/chat-sdk-javascript"; import { CometChatAIAssistantChat } from "@cometchat/chat-uikit-react"; -export function AIAssistantChatDemo() { - const [agent, setAgent] = React.useState(); - - React.useEffect(() => { - CometChat.getUser("assistant_uid").then((u) => setAgent(u)); - }, []); +function AIAssistantCustomImage() { + const [agent, setAgent] = useState(); - const handleSendButton = () => { - // your custom action - }; + useEffect(() => { + CometChat.getUser("assistant_uid").then((u) => setAgent(u)); + }, []); - if (!agent) return null; + if (!agent) return null; - return ( - - ); + return ( + } + /> + ); } ``` - +### emptyChatGreetingView - -```jsx -import React from "react"; + + + + + + +```tsx +import { useState, useEffect } from "react"; import { CometChat } from "@cometchat/chat-sdk-javascript"; import { CometChatAIAssistantChat } from "@cometchat/chat-uikit-react"; -export function AIAssistantChatDemo() { - const [agent, setAgent] = React.useState(null); - - React.useEffect(() => { - CometChat.getUser("assistant_uid").then((u) => setAgent(u)); - }, []); +function AIAssistantCustomGreeting() { + const [agent, setAgent] = useState(); - const handleSendButton = () => { - // your custom action - }; + useEffect(() => { + CometChat.getUser("assistant_uid").then((u) => setAgent(u)); + }, []); - if (!agent) return null; + if (!agent) return null; - return ( - - ); + return ( + + Free Plan . + Upgrade + + } + /> + ); } ``` + + +```css +.cometchat-ai-assistant-chat__empty-chat-greeting { + display: flex; + padding: 8px 20px; + justify-content: center; + align-items: center; + gap: 8px; + border-radius: 6px; + border: 1px solid #e8e8e8; + background: #f5f5f5; + width: fit-content; + align-self: center; +} +.cometchat-ai-assistant-chat__empty-chat-greeting .upgrade-button { + color: #6852d6; +} +``` -##### 4. onError +### emptyChatIntroMessageView -Listen to errors from the underlying header, list, or composer. + + + ```tsx -import React from "react"; +import { useState, useEffect } from "react"; import { CometChat } from "@cometchat/chat-sdk-javascript"; import { CometChatAIAssistantChat } from "@cometchat/chat-uikit-react"; -export function AIAssistantChatDemo() { - const [agent, setAgent] = React.useState(); - React.useEffect(() => { - CometChat.getUser("assistant_uid").then((u) => setAgent(u)); - }, []); +function AIAssistantCustomIntro() { + const [agent, setAgent] = useState(); - const handleError = (error: CometChat.CometChatException) => { - // your error handling - }; + useEffect(() => { + CometChat.getUser("assistant_uid").then((u) => setAgent(u)); + }, []); - if (!agent) return null; + if (!agent) return null; - return ( - - ); + return ( + + Hey, nice to see you What's new? + + } + /> + ); } ``` + +```css +.cometchat-ai-assistant-chat__empty-chat-intro { + display: flex; + padding: 12px; + justify-content: center; + align-items: center; + gap: 10px; + border-radius: 12px; + background: #f9f8fd; + width: 172px; + color: #141414; + text-align: center; + font-size: 16px; + font-weight: 400; + line-height: 140%; + margin: 10px 0; +} +``` + + + +### aiAssistantTools - -```jsx -import React from "react"; +Pass a `CometChatAIAssistantTools` instance to enable tool/function calls during assistant replies. + +```tsx +import { useState, useEffect } from "react"; import { CometChat } from "@cometchat/chat-sdk-javascript"; -import { CometChatAIAssistantChat } from "@cometchat/chat-uikit-react"; -export function AIAssistantChatDemo() { - const [agent, setAgent] = React.useState(null); +import { + CometChatAIAssistantChat, + CometChatAIAssistantTools, +} from "@cometchat/chat-uikit-react"; + +function AIAssistantWithTools() { + const [agent, setAgent] = useState(); - React.useEffect(() => { - CometChat.getUser("assistant_uid").then((u) => setAgent(u)); - }, []); + useEffect(() => { + CometChat.getUser("assistant_uid").then((u) => setAgent(u)); + }, []); - const handleError = (error: CometChat.CometChatException) => { - // your error handling - }; + const tools = new CometChatAIAssistantTools({ + getCurrentWeather: ({ location }: { location: string }) => { + console.log("Fetching weather for", location); + }, + createTicket: ({ title }: { title: string }) => { + console.log("Create ticket:", title); + }, + }); - if (!agent) return null; + if (!agent) return null; - return ( - - ) + return ; } ``` - - +### templates +Custom message templates to control message bubble rendering. See [CometChatMessageTemplate](/ui-kit/react/message-template). ---- +```tsx +import { useState, useEffect } from "react"; +import { CometChat } from "@cometchat/chat-sdk-javascript"; +import { + CometChatAIAssistantChat, + ChatConfigurator, +} from "@cometchat/chat-uikit-react"; -## Customization +function AIAssistantWithTemplates() { + const [agent, setAgent] = useState(); -To fit your app’s design requirements, you can customize the appearance of the Assistant Chat component. We provide exposed properties that allow you to modify the experience and behavior according to your specific needs. + useEffect(() => { + CometChat.getUser("assistant_uid").then((u) => setAgent(u)); + }, []); -### Style + const getTemplates = () => { + const templates = ChatConfigurator.getDataSource().getAllMessageTemplates(); + templates.map((data) => { + data.footerView = (message) => null; + }); + return templates; + }; -You can set the css of the Assistant Chat Component to customize the styling. + if (!agent) return null; - - - + return ; +} +``` + +--- + +## Common Patterns + +### AI assistant with suggestions and history - - ```tsx -import React from "react"; +import { useState, useEffect } from "react"; import { CometChat } from "@cometchat/chat-sdk-javascript"; import { CometChatAIAssistantChat } from "@cometchat/chat-uikit-react"; -export function AIAssistantChatDemo = () => { - const [agent, setAgent] = React.useState(); - - React.useEffect(() => { - CometChat.getUser("assistant_uid").then((u) => setAgent(u)); - }, []); +function FullFeaturedAssistant() { + const [agent, setAgent] = useState(); - if (!agent) return null; + useEffect(() => { + CometChat.getUser("assistant_uid").then((u) => setAgent(u)); + }, []); - return ( -
- -
- ); + if (!agent) return null; + + return ( + console.log("Navigate back")} + /> + ); } ``` -
+### Minimal assistant — no chrome - -```jsx -import React from "react"; +```tsx +import { useState, useEffect } from "react"; import { CometChat } from "@cometchat/chat-sdk-javascript"; import { CometChatAIAssistantChat } from "@cometchat/chat-uikit-react"; -export function AIAssistantChatDemo = () => { - const [agent, setAgent] = React.useState(null); +function MinimalAssistant() { + const [agent, setAgent] = useState(); - React.useEffect(() => { - CometChat.getUser("assistant_uid").then((u) => setAgent(u)); - }, []); + useEffect(() => { + CometChat.getUser("assistant_uid").then((u) => setAgent(u)); + }, []); - if (!agent) return null; + if (!agent) return null; - return ( -
- -
- ); + return ( + + ); } ``` -
+--- + +## CSS Architecture + +The component uses CSS custom properties (design tokens) defined in `@cometchat/chat-uikit-react/css-variables.css`. The cascade: + +1. Global tokens (e.g., `--cometchat-primary-color`, `--cometchat-background-color-01`) set on the `.cometchat` root wrapper. +2. Component CSS (`.cometchat-ai-assistant-chat`) consumes these tokens via `var()`. +3. Overrides target `.cometchat-ai-assistant-chat` descendant selectors. + +### Key Selectors + +| Target | Selector | +| --- | --- | +| Root | `.cometchat-ai-assistant-chat` | +| Wrapper | `.cometchat-ai-assistant-chat__wrapper` | +| Header wrapper | `.cometchat-ai-assistant-chat__header-wrapper` | +| Header auxiliary view | `.cometchat-ai-assistant-chat__header-auxiliary-view` | +| Message list wrapper | `.cometchat-ai-assistant-chat__message-list-wrapper` | +| Composer wrapper | `.cometchat-ai-assistant-chat__composer-wrapper` | +| Send button | `.cometchat-ai-assistant-chat__send-button-view` | +| Send button (active) | `.cometchat-ai-assistant-chat__send-button-view--active` | +| Send button (streaming) | `.cometchat-ai-assistant-chat__send-button-view--streaming` | +| Empty state | `.cometchat-ai-assistant-chat__empty-state` | +| Empty state content | `.cometchat-ai-assistant-chat__empty-state-content` | +| Empty state icon | `.cometchat-ai-assistant-chat__empty-state-icon` | +| Greeting message | `.cometchat-ai-assistant-chat__empty-state-greeting-message` | +| Intro message | `.cometchat-ai-assistant-chat__empty-state-intro-message` | +| Suggested messages | `.cometchat-ai-assistant-chat__empty-state-suggested-messages` | +| Suggestion pill | `.cometchat-ai-assistant-chat__suggested-message-pill` | +| Suggestion icon | `.cometchat-ai-assistant-chat__suggested-message-icon` | +| Chat history sidebar | `.cometchat-ai-assistant-chat__sidebar` | +| Sidebar open | `.cometchat-ai-assistant-chat__sidebar--open` | +| Sidebar overlay | `.cometchat-ai-assistant-chat__sidebar-overlay` | +| Copy button | `.cometchat-ai-assistant-message-bubble__copy` | + +### Example: Brand-themed AI assistant + + + + - ```css .cometchat-ai-assistant-chat .cometchat-ai-assistant-chat__suggested-message-pill { - background: #30a46c; - color: #ffffff; - text-align: center; - font-family: "Times New Roman"; - font-size: 9px; - font-style: normal; - font-weight: 400; - line-height: 120%; + background: #30a46c; + color: #ffffff; + font-size: 9px; } .cometchat-ai-assistant-chat .cometchat-ai-assistant-chat__suggested-message-pill .cometchat-ai-assistant-chat__suggested-message-icon { - background: #ffffff; - width: 9.55px; - height: 9.55px; + background: #ffffff; + width: 9.55px; + height: 9.55px; } + .cometchat-ai-assistant-chat .cometchat-ai-assistant-chat__header-auxiliary-view .cometchat-button .cometchat-button__icon-default { - background: #30a46c; + background: #30a46c; } ``` - -
+### Customization Matrix -### Functionality +| What to change | Where | Property/API | Example | +| --- | --- | --- | --- | +| Override behavior on user interaction | Component props | `on` callbacks | `onBackButtonClicked={() => navigate(-1)}` | +| Toggle visibility of UI elements | Component props | `hide` / `show` boolean props | `hideNewChat={true}` | +| Replace a section of the UI | Component props | View slot props | `emptyChatGreetingView={
Hello
}` | +| Change colors, fonts, spacing | Global CSS | Target `.cometchat-ai-assistant-chat` class | `.cometchat-ai-assistant-chat .cometchat-ai-assistant-chat__suggested-message-pill { background: #30a46c; }` | -These props tailor the experience. Most message options (copy/edit/delete/react, receipts, date separators, etc.) are disabled by default for assistant chats. +--- - - -```tsx -import React from "react"; -import { CometChat } from "@cometchat/chat-sdk-javascript"; -import { CometChatAIAssistantChat } from "@cometchat/chat-uikit-react"; +## Accessibility -export function AIAssistantChatDemo = () => { - const [agent, setAgent] = React.useState(); - - React.useEffect(() => { - CometChat.getUser("assistant_uid").then((u) => setAgent(u)); - }, []); - - if (!agent) return null; - - // Example: Set streaming speed to 30 characters per second - // and show close button - // You can also customize suggestions, empty state, etc. - return ( - - ) -} -``` +The component composes `CometChatMessageHeader`, `CometChatMessageList`, and `CometChatMessageComposer` internally. Keyboard navigation, focus management, and ARIA attributes are inherited from those components. Suggested message pills are keyboard-focusable and activate on Enter/Space. The chat history sidebar uses a backdrop overlay and traps focus when open. - +--- - -```jsx -import React from "react"; -import { CometChat } from "@cometchat/chat-sdk-javascript"; -import { CometChatAIAssistantChat } from "@cometchat/chat-uikit-react"; +--- -export function AIAssistantChatDemo = () => { - const [agent, setAgent] = React.useState(null); - - React.useEffect(() => { - CometChat.getUser("assistant_uid").then((u) => setAgent(u)); - }, []); - - if (!agent) return null; - - // Example: Set streaming speed to 30 characters per second - // and show close button - // You can also customize suggestions, empty state, etc. - return ( - - ); -} -``` +## Props - - +### aiAssistantTools + +| Key | Value | +| --- | --- | +| Type | `CometChatAIAssistantTools` | +| Default | `undefined` | + +Tool/function call handlers for the AI assistant. --- -| Property | Description | Example | -| --------------------------- | ------------------------------------------------------------------------------------------------------------ | --------------------------------------- | -| `user` | Required `CometChat.User` representing the AI agent. | `user={agent}` | -| `streamingSpeed` | Characters-per-second speed for streaming replies. Default `30`. | `streamingSpeed={50}` | -| `suggestedMessages` | Array of quick prompts for the empty state. | `suggestedMessages=["Help", "Summarize"]` | -| `hideSuggestedMessages` | Hide the suggestions section. | `hideSuggestedMessages={true}` | -| `hideNewChat` | Hide the New Chat button in header. | `hideNewChat={true}` | -| `hideChatHistory` | Hide the History button/sidebar. | `hideChatHistory={true}` | -| `showBackButton` | Show back button in header. | `showBackButton` | -| `showCloseButton` | Show close button in header. | `showCloseButton` | -| `onBackButtonClicked` | Back button handler. | `onBackButtonClicked={() => {}}` | -| `onCloseButtonClicked` | Close button handler. | `onCloseButtonClicked={() => {}}` | -| `onSendButtonClick` | Send button handler. | `onSendButtonClick={() => {}}` | -| `onError` | Error handler. | `onError={handleError}` | -| `emptyView` | Custom empty state for the list. | `emptyView={}` | -| `loadingView` | Custom loading view. | `loadingView={}` | -| `errorView` | Custom error view. | `errorView={}` | -| `emptyChatGreetingView` | Custom empty title (default uses metadata.greetingMessage or user name). | `emptyChatGreetingView={

}` | -| `emptyChatIntroMessageView` | Custom empty subtitle (default uses metadata.introductoryMessage). | `emptyChatIntroMessageView={

}` | -| `emptyChatImageView` | Custom empty image. | `emptyChatImageView={}` | -| `aiAssistantTools` | Provide tool/function handlers for the assistant. | `aiAssistantTools={tools}` | -| `loadLastAgentConversation` | Loads the most recent existing agent conversation if one is available. | `loadLastAgentConversation={true}` | -| `parentMessageId` | The parent message ID to load a specific agent conversation. Takes priority over `loadLastAgentConversation`. | `parentMessageId={12345}` | +### emptyView -### Advanced +| Key | Value | +| --- | --- | +| Type | `React.JSX.Element` | +| Default | `undefined` | -#### Header Views +Custom empty state for the message list. -Customize header sections using the following props: `headerItemView`, `headerTitleView`, `headerSubtitleView`, `headerLeadingView`, `headerTrailingView`, and `headerAuxiliaryButtonView`. These customizations are done in the similar way as the [Message Header](/ui-kit/react/message-header#advanced) component. +--- - -The header’s "New Chat" and "History" buttons are built-in. You can override them by providing a custom `headerAuxiliaryButtonView`. - +### emptyChatGreetingView -#### Assistant Tools +| Key | Value | +| --- | --- | +| Type | `React.JSX.Element` | +| Default | `undefined` | -Pass an instance of `CometChatAIAssistantTools` to enable tool/function calls during assistant replies. +Custom greeting title in the empty chat state. Default uses agent metadata `greetingMessage` or user name. - - -```tsx -import React from "react"; -import { CometChat } from "@cometchat/chat-sdk-javascript"; -import { CometChatAIAssistantChat } from "@cometchat/chat-uikit-react"; -import { CometChatAIAssistantTools } from "@cometchat/chat-uikit-react"; - -export function AIAssistantChatDemo = () => { - const [agent, setAgent] = React.useState(); - - React.useEffect(() => { - CometChat.getUser("assistant_uid").then((u) => setAgent(u)); - }, []); - - const tools = new CometChatAIAssistantTools({ - getCurrentWeather: ({ location }: { location: string }) => { - // call your backend or a public API - console.log("Fetching weather for", location); - }, - createTicket: ({ title }: { title: string }) => { - // open your internal ticketing flow - console.log("Create ticket:", title); - }, - }); +--- - if (!agent) return null; +### emptyChatImageView - return ( - - ); -``` +| Key | Value | +| --- | --- | +| Type | `React.JSX.Element` | +| Default | `undefined` | - +Custom image in the empty chat state. - -```jsx -import React from "react"; -import { CometChat } from "@cometchat/chat-sdk-javascript"; -import { CometChatAIAssistantChat } from "@cometchat/chat-uikit-react"; -import { CometChatAIAssistantTools } from "@cometchat/chat-uikit-react"; - -export function AIAssistantChatDemo = () => { - const [agent, setAgent] = React.useState(null); - - React.useEffect(() => { - CometChat.getUser("assistant_uid").then((u) => setAgent(u)); - }, []); - - const tools = new CometChatAIAssistantTools({ - getCurrentWeather: ({ location }: { location: string }) => { - // call your backend or a public API - console.log("Fetching weather for", location); - }, - createTicket: ({ title }: { title: string }) => { - // open your internal ticketing flow - console.log("Create ticket:", title); - }, - }); +--- - if (!agent) return null; +### emptyChatIntroMessageView - return ( - - ); -} -``` +| Key | Value | +| --- | --- | +| Type | `React.JSX.Element` | +| Default | `undefined` | - - +Custom intro subtitle in the empty chat state. Default uses agent metadata `introductoryMessage`. -#### Empty Chat Image View +--- -Provide a custom image for the empty state using `emptyChatImageView`. +### errorView - - - +| Key | Value | +| --- | --- | +| Type | `React.JSX.Element` | +| Default | `undefined` | - - -```tsx -import React from "react"; -import { CometChat } from "@cometchat/chat-sdk-javascript"; -import { CometChatAIAssistantChat } from "@cometchat/chat-uikit-react"; +Custom error state view. -export function AIAssistantChatDemo() { - const [agent, setAgent] = React.useState(); +--- - React.useEffect(() => { - CometChat.getUser("assistant_uid").then((u) => setAgent(u)); - }, []); +### headerAuxiliaryButtonView - if (!agent) return null; +| Key | Value | +| --- | --- | +| Type | `React.JSX.Element` | +| Default | `undefined` | - return ( - } - /> - ); -} -``` +Replaces the header auxiliary buttons (New Chat, History). - +--- - -```jsx -import React from "react"; -import { CometChat } from "@cometchat/chat-sdk-javascript"; -import { CometChatAIAssistantChat } from "@cometchat/chat-uikit-react"; +### headerItemView -export function AIAssistantChatDemo() { - const [agent, setAgent] = React.useState(null); +| Key | Value | +| --- | --- | +| Type | `React.JSX.Element` | +| Default | `undefined` | - React.useEffect(() => { - CometChat.getUser("assistant_uid").then((u) => setAgent(u)); - }, []); +Replaces the entire header list item. - if (!agent) return null; +--- - return ( - } - /> - ) -} -``` +### headerLeadingView - - +| Key | Value | +| --- | --- | +| Type | `React.JSX.Element` | +| Default | `undefined` | -#### Empty Chat Greeting View +Replaces the header avatar / left section. -Override the empty state greeting message view using the `emptyChatGreetingView` prop. +--- - - - +### headerSubtitleView - - -```tsx -import React from "react"; -import { CometChat } from "@cometchat/chat-sdk-javascript"; -import { CometChatAIAssistantChat } from "@cometchat/chat-uikit-react"; +| Key | Value | +| --- | --- | +| Type | `React.JSX.Element` | +| Default | `undefined` | -export function AIAssistantChatDemo() { - const [agent, setAgent] = React.useState(); - - React.useEffect(() => { - CometChat.getUser("assistant_uid").then((u) => setAgent(u)); - }, []); - - if (!agent) return null; - - return ( - - Free Plan . - Upgrade - - } - /> - ); -} -``` +Replaces the header subtitle text. - +--- - -```jsx -import React from "react"; -import { CometChat } from "@cometchat/chat-sdk-javascript"; -import { CometChatAIAssistantChat } from "@cometchat/chat-uikit-react"; +### headerTitleView -export function AIAssistantChatDemo() { - const [agent, setAgent] = React.useState(null); - - React.useEffect(() => { - CometChat.getUser("assistant_uid").then((u) => setAgent(u)); - }, []); - - if (!agent) return null; - - return ( - - Free Plan . - Upgrade - - } - /> - ) -} -``` +| Key | Value | +| --- | --- | +| Type | `React.JSX.Element` | +| Default | `undefined` | - +Replaces the header title text. - -```css -.cometchat-ai-assistant-chat__empty-chat-greeting { - display: flex; - padding: 8px 20px; - justify-content: center; - align-items: center; - gap: 8px; - flex: 1 0 0; - align-self: stretch; - border-radius: 6px; - border: 1px solid #e8e8e8; - background: #f5f5f5; - width: fit-content; - align-self: center; -} +--- -.cometchat-ai-assistant-chat__empty-chat-greeting .upgrade-button { - color: #6852d6; -} -``` - - +### headerTrailingView -#### Empty Chat Intro Message View +| Key | Value | +| --- | --- | +| Type | `React.JSX.Element` | +| Default | `undefined` | -You can override the empty chat intro message view using the `emptyChatIntroMessageView` prop. +Replaces the header right section. - - - +--- - - -```tsx -import React from "react"; -import { CometChat } from "@cometchat/chat-sdk-javascript"; -import { CometChatAIAssistantChat } from "@cometchat/chat-uikit-react"; +### hideChatHistory -export function AIAssistantChatDemo() { - const [agent, setAgent] = React.useState(); - - React.useEffect(() => { - CometChat.getUser("assistant_uid").then((u) => setAgent(u)); - }, []); - - if (!agent) return null; - - return ( - - Hey, nice to see you What’s new? - - } - /> - ); -} -``` +| Key | Value | +| --- | --- | +| Type | `boolean` | +| Default | `undefined` | - +Hides the History button/sidebar. - -```jsx -import React from "react"; -import { CometChat } from "@cometchat/chat-sdk-javascript"; -import { CometChatAIAssistantChat } from "@cometchat/chat-uikit-react"; +--- -export function AIAssistantChatDemo() { - const [agent, setAgent] = React.useState(null); - - React.useEffect(() => { - CometChat.getUser("assistant_uid").then((u) => setAgent(u)); - }, []); - - if (!agent) return null; - - return ( - - Hey, nice to see you What’s new? - - } - /> - ); -} -``` +### hideNewChat - +| Key | Value | +| --- | --- | +| Type | `boolean` | +| Default | `undefined` | - -```css -.cometchat-ai-assistant-chat__empty-chat-intro { - display: flex; - padding: 12px; - justify-content: center; - align-items: center; - gap: 10px; - border-radius: 12px; - background: #f9f8fd; - width: 172px; - color: #141414; - text-align: center; - font-family: Inter; - font-size: 16px; - font-style: normal; - font-weight: 400; - line-height: 140%; - margin: 10px 0; -} -``` - - +Hides the New Chat button in header. -#### Templates +--- -[CometChatMessageTemplate](/ui-kit/react/message-template) is a pre-defined structure for creating message views that can be used as a starting point or blueprint for creating message views often known as message bubbles. For more information, you can refer to [CometChatMessageTemplate](/ui-kit/react/message-template). +### hideSuggestedMessages -You can set message Templates to AIAssistantChat by using the following code snippet. +| Key | Value | +| --- | --- | +| Type | `boolean` | +| Default | `undefined` | - - -```ts -import React from "react"; -import { CometChat } from "@cometchat/chat-sdk-javascript"; -import { - CometChatAIAssistantChat, - ChatConfigurator -} from "@cometchat/chat-uikit-react"; +Hides the suggested messages section in the empty state. -export function AIAssistantChatDemo() { - const [chatUser, setChatUser] = React.useState(); - React.useEffect(() => { - CometChat.getUser("uid").then((user) => { - setChatUser(user); - }); - }, []); +--- - const getTemplates = () => { - let templates = ChatConfigurator.getDataSource().getAllMessageTemplates(); - templates.map((data) => { - data.footerView = (message) => {}; //custom view here - }); - return templates; - }; +### loadLastAgentConversation - return chatUser ? ( -

- -
- ) : null; -} -``` +| Key | Value | +| --- | --- | +| Type | `boolean` | +| Default | `false` | - +Loads the most recent existing agent conversation on mount. - -```js -import React from "react"; -import { CometChat } from "@cometchat/chat-sdk-javascript"; -import { - CometChatAIAssistantChat, - ChatConfigurator -} from "@cometchat/chat-uikit-react"; +--- -export function AIAssistantChatDemo() { - const [chatUser, setChatUser] = React.useState(null); +### loadingView - React.useEffect(() => { - CometChat.getUser("uid").then((user) => { - setChatUser(user); - }); - }, []); +| Key | Value | +| --- | --- | +| Type | `React.JSX.Element` | +| Default | `undefined` | - const getTemplates = () => { - let templates = ChatConfigurator.getDataSource().getAllMessageTemplates(); - templates.map((data) => { - data.footerView = (message) => {}; //custom view here - }); - return templates; - }; +Custom loading state view. - return chatUser ? ( -
- -
- ) : null; -} -``` +--- -
+### onBackButtonClicked - +| Key | Value | +| --- | --- | +| Type | `() => void` | +| Default | `undefined` | + +Fires when the header back button is clicked. Requires `showBackButton={true}`. + +--- + +### onCloseButtonClicked + +| Key | Value | +| --- | --- | +| Type | `() => void` | +| Default | `undefined` | + +Fires when the header close button is clicked. Requires `showCloseButton={true}`. + +--- + +### onError + +| Key | Value | +| --- | --- | +| Type | `(e: CometChat.CometChatException) => void` | +| Default | `undefined` | + +Fires on internal errors. + +--- + +### onSendButtonClick + +| Key | Value | +| --- | --- | +| Type | `(message: CometChat.BaseMessage, previewMessageMode?: PreviewMessageMode) => void` | +| Default | `undefined` | + +Fires when the composer send button is clicked. + +--- + +### parentMessageId + +| Key | Value | +| --- | --- | +| Type | `number` | +| Default | `undefined` | + +Loads a specific agent conversation. Takes priority over `loadLastAgentConversation`. + +--- + +### showBackButton + +| Key | Value | +| --- | --- | +| Type | `boolean` | +| Default | `undefined` | + +Shows back button in header. + +--- + +### showCloseButton + +| Key | Value | +| --- | --- | +| Type | `boolean` | +| Default | `undefined` | + +Shows close button in header. + +--- + +### streamingSpeed + +| Key | Value | +| --- | --- | +| Type | `number` | +| Default | `undefined` | + +Characters-per-second speed for streaming replies. + +--- + +### suggestedMessages + +| Key | Value | +| --- | --- | +| Type | `string[]` | +| Default | `undefined` | + +Quick prompt suggestions displayed in the empty state. + +--- + +### templates + +| Key | Value | +| --- | --- | +| Type | `CometChatMessageTemplate[]` | +| Default | `undefined` | + +Custom message bubble templates. See [CometChatMessageTemplate](/ui-kit/react/message-template). + +--- + +### user + +| Key | Value | +| --- | --- | +| Type | `CometChat.User` | +| Default | — (required) | + +The AI agent user object. Must be fetched via `CometChat.getUser()` before passing. + +--- -*** +## CSS Selectors + +| Target | Selector | +| --- | --- | +| Root | `.cometchat-ai-assistant-chat` | +| Wrapper | `.cometchat-ai-assistant-chat__wrapper` | +| Header wrapper | `.cometchat-ai-assistant-chat__header-wrapper` | +| Header auxiliary view | `.cometchat-ai-assistant-chat__header-auxiliary-view` | +| Message list wrapper | `.cometchat-ai-assistant-chat__message-list-wrapper` | +| Composer wrapper | `.cometchat-ai-assistant-chat__composer-wrapper` | +| Send button | `.cometchat-ai-assistant-chat__send-button-view` | +| Send button (active) | `.cometchat-ai-assistant-chat__send-button-view--active` | +| Send button (streaming) | `.cometchat-ai-assistant-chat__send-button-view--streaming` | +| Empty state | `.cometchat-ai-assistant-chat__empty-state` | +| Empty state content | `.cometchat-ai-assistant-chat__empty-state-content` | +| Empty state icon | `.cometchat-ai-assistant-chat__empty-state-icon` | +| Greeting message | `.cometchat-ai-assistant-chat__empty-state-greeting-message` | +| Intro message | `.cometchat-ai-assistant-chat__empty-state-intro-message` | +| Suggested messages | `.cometchat-ai-assistant-chat__empty-state-suggested-messages` | +| Suggestion pill | `.cometchat-ai-assistant-chat__suggested-message-pill` | +| Suggestion icon | `.cometchat-ai-assistant-chat__suggested-message-icon` | +| Chat history sidebar | `.cometchat-ai-assistant-chat__sidebar` | +| Sidebar open | `.cometchat-ai-assistant-chat__sidebar--open` | +| Sidebar overlay | `.cometchat-ai-assistant-chat__sidebar-overlay` | +| Copy button | `.cometchat-ai-assistant-message-bubble__copy` | diff --git a/ui-kit/react/ai-features.mdx b/ui-kit/react/ai-features.mdx index c0f24be3b..04e2188e3 100644 --- a/ui-kit/react/ai-features.mdx +++ b/ui-kit/react/ai-features.mdx @@ -1,47 +1,65 @@ --- -title: "AI User Copilot" +title: "Smart Chat Features" +description: "AI-powered features in CometChat's React UI Kit: Conversation Starter, Smart Replies, and Conversation Summary." --- -## Overview + +- **Package:** `@cometchat/chat-uikit-react` +- **Required setup:** `CometChatUIKit.init(UIKitSettings)` then `CometChatUIKit.login("UID")` + AI features enabled in [CometChat Dashboard](/fundamentals/ai-user-copilot/overview) +- **AI features:** Conversation Starter, Smart Replies, Conversation Summary +- **Key components:** `CometChatMessageList` → [Message List](/ui-kit/react/message-list) (Conversation Starter), `CometChatMessageComposer` → [Message Composer](/ui-kit/react/message-composer) (Smart Replies, Summary), `CometChatAIAssistantChat` → [AI Assistant Chat](/ui-kit/react/ai-assistant-chat) +- **Activation:** Enable each AI feature from the CometChat Dashboard — UI Kit auto-integrates them, no additional code required + -CometChat's AI capabilities greatly enhance user interaction and engagement in your application. Let's understand how the React UI Kit achieves these features. +## Overview - - - +CometChat AI features enhance user interaction by providing contextual suggestions and summaries. Each feature is activated from the Dashboard and auto-integrates into UI Kit components. -## Conversation Starters +## Smart Chat Features -When a user initiates a new chat, the UI kit displays a list of suggested opening lines that users can select, making it easier for them to start a conversation. These suggestions are powered by CometChat's AI, which predicts contextually relevant conversation starters. +### Conversation Starter -For a comprehensive understanding and guide on implementing and using the Conversation Starters, refer to our specific guide on the [Conversation Starter](/fundamentals/ai-user-copilot/conversation-starter). +Displays AI-generated opening lines when a user starts a new chat. See [Conversation Starter](/fundamentals/ai-user-copilot/conversation-starter). -Once you have successfully activated the [Conversation Starter](/fundamentals/ai-user-copilot/conversation-starter) from your CometChat Dashboard, the feature will automatically be incorporated into the [MessageList](/ui-kit/react/message-list) Component of UI Kits. +Auto-integrates into [MessageList](/ui-kit/react/message-list) when activated. -## Smart Replies +### Smart Replies -Smart Replies are AI-generated responses to messages. They can predict what a user might want to say next by analyzing the context of the conversation. This allows for quicker and more convenient responses, especially on mobile devices. +AI-generated response suggestions based on conversation context. See [Smart Replies](/fundamentals/ai-user-copilot/smart-replies). -For a comprehensive understanding and guide on implementing and using the Smart Replies, refer to our specific guide on the [Smart Replies](/fundamentals/ai-user-copilot/smart-replies). - -Once you have successfully activated the [Smart Replies](/fundamentals/ai-user-copilot/smart-replies) from your CometChat Dashboard, the feature will automatically be incorporated into the Action sheet of [MessageComposer](/ui-kit/react/message-composer) Component of UI Kits. +Auto-integrates into the Action Sheet of [MessageComposer](/ui-kit/react/message-composer) when activated. -## Conversation Summary - -The Conversation Summary feature provides concise summaries of long conversations, allowing users to catch up quickly on missed chats. This feature uses natural language processing to determine the main points in a conversation. +### Conversation Summary -For a comprehensive understanding and guide on implementing and using the Conversation Summary, refer to our specific guide on the [Conversation Summary](/fundamentals/ai-user-copilot/conversation-summary). +AI-generated recap of long conversations. See [Conversation Summary](/fundamentals/ai-user-copilot/conversation-summary). -Once you have successfully activated the [Conversation Summary](/fundamentals/ai-user-copilot/conversation-summary) from your CometChat Dashboard, the feature will automatically be incorporated into the Action sheet of [MessageComposer](/ui-kit/react/message-composer) Component of UI Kits. +Auto-integrates into the Action Sheet of [MessageComposer](/ui-kit/react/message-composer) when activated. + +## Next Steps + + + + AI-powered assistant component + + + Customize the message list where AI features appear + + + Customize the composer with Smart Replies and Summary + + + Core chat features like messaging and reactions + + diff --git a/ui-kit/react/astro-conversation.mdx b/ui-kit/react/astro-conversation.mdx index 605b47376..c86795d53 100644 --- a/ui-kit/react/astro-conversation.mdx +++ b/ui-kit/react/astro-conversation.mdx @@ -1,11 +1,19 @@ --- title: "Building a Conversation List + Message View in Astro" sidebarTitle: "Conversation List + Message View" +description: "Build a two-panel conversation list + message view layout in Astro with CometChat React UI Kit." --- -The Conversation List + Message View layout provides a familiar two‑panel experience, similar to WhatsApp Web or Slack. Users browse conversations on the left and chat in real time on the right. + +- **Package:** `@cometchat/chat-uikit-react` +- **Framework:** Astro (with `@astrojs/react` islands) +- **Key component:** `CometChatConversationsWithMessages` +- **Required setup:** `CometChatUIKit.init(UIKitSettings)` then `CometChatUIKit.login("UID")` — use `client:only="react"` directive +- **Parent guide:** [Astro Integration](/ui-kit/react/astro-integration) + + -*** +The Conversation List + Message View layout provides a familiar two‑panel experience, similar to WhatsApp Web or Slack. Users browse conversations on the left and chat in real time on the right. ## User Interface Overview @@ -15,11 +23,9 @@ The Conversation List + Message View layout provides a familiar two‑panel expe This layout includes: -1. Sidebar (Conversation List) – Users and groups -2. Message View – Real-time messages for the selected conversation -3. Message Composer – Input for sending text and media - -*** +1. Sidebar (Conversation List) — Users and groups +2. Message View — Real-time messages for the selected conversation +3. Message Composer — Input for sending text and media ## Prerequisites @@ -31,7 +37,7 @@ This layout includes: - ```bash + ```bash lines npm create astro@latest cd my-astro-app npm install @@ -239,9 +245,25 @@ This layout includes: - ```bash - npm run dev - ``` + + + ```bash lines + npm run dev + ``` + + + + ```bash lines + pnpm dev + ``` + + + + ```bash lines + yarn dev + ``` + + Open your app and verify you can select conversations on the left and exchange messages on the right. @@ -249,8 +271,6 @@ This layout includes: -*** - ## Troubleshooting @@ -267,16 +287,21 @@ The sample uses `ensureLogin(uid)` to switch users by logging out if the active -*** +For prop details and customization options, see the component reference pages: [CometChatConversations](/ui-kit/react/conversations), [CometChatMessageList](/ui-kit/react/message-list), [CometChatMessageComposer](/ui-kit/react/message-composer), [CometChatMessageHeader](/ui-kit/react/message-header). ## Next Steps - -- Customize styles in `src/styles/cometchat-layout.css` -- Add presence or typing indicators -- Explore themes and component overrides in the UI Kit + + + Browse all available UI components. + + + Astro setup guide. + + + Core chat features. + + To build other experiences (One‑to‑One or Tab‑based), reuse `src/lib/cometchat-init.js` and switch the React island component. - - diff --git a/ui-kit/react/astro-integration.mdx b/ui-kit/react/astro-integration.mdx index 6ae758a65..cd78b6a8b 100644 --- a/ui-kit/react/astro-integration.mdx +++ b/ui-kit/react/astro-integration.mdx @@ -1,108 +1,56 @@ --- title: "Getting Started With CometChat React UI Kit in Astro" sidebarTitle: "Integration" +description: "Step-by-step guide to integrate CometChat React UI Kit into your Astro application using @astrojs/react islands." --- -The CometChat platform lets you add in‑app chat with minimal effort. In Astro, you can integrate CometChat in two primary ways: + +- **Package:** `@cometchat/chat-uikit-react` — `npm install @cometchat/chat-uikit-react` + `npx astro add react` +- **Required setup:** `CometChatUIKit.init(UIKitSettings)` then `CometChatUIKit.login("UID")` — must complete before rendering +- **SSR:** CometChat requires browser APIs — use `client:only="react"` directive on Astro islands +- **Init code:** `new UIKitSettingsBuilder().setAppId("APP_ID").setRegion("REGION").setAuthKey("AUTH_KEY").build()` +- **Framework:** Astro (this page) | [React.js](/ui-kit/react/react-js-integration) | [Next.js](/ui-kit/react/next-js-integration) | [React Router](/ui-kit/react/react-router-integration) +- **All components:** [Components Overview](/ui-kit/react/components-overview) + -- Using the CometChat JavaScript SDK directly for framework-agnostic control -- Using the CometChat React UI Kit via the `@astrojs/react` integration to get prebuilt, themeable chat UI - -This guide shows you CometChat React UI Kit Integration so you can quickly enable one-to-one and group messaging in your Astro app. +The CometChat UI Kit for React provides prebuilt UI components for in-app chat. In Astro, integrate via the `@astrojs/react` integration to get themeable chat UI with `client:only="react"` islands. CometChat prebuilt chat UI screens overview - -*** - -*** - ## Prerequisites -Before installing the CometChat SDK or UI Kit, create a CometChat application in the [CometChat Dashboard](https://app.cometchat.com/). The dashboard provides core services including: - -- User Management -- Group Chat & Messaging -- Voice & Video Calling -- Real-time Notifications - -> To initialize CometChat you need the following from your application: -> -> 1. App ID -> 2. Auth Key -> 3. Region -> -> Keep these ready for the configuration steps below. - -*** - -## Register & Set Up CometChat - -Follow these steps to register and prepare your environment. - -### Step 1: Register on CometChat - -Sign up or log in to the CometChat Dashboard. - -🔗 **[Sign in to CometChat](https://app.cometchat.com/login)** - -### Step 2: Get Your Application Keys +Create a CometChat application via the [CometChat Dashboard](https://app.cometchat.com/). The dashboard provides user management, group chat, voice/video calling, and real-time notifications. -Create a new app and copy your credentials: +Required credentials from the dashboard: -1. Go to your App → Credentials -2. Note the App ID, Auth Key, and Region - - - Each CometChat application can power a single client app. Users in the same app can chat across platforms (web and mobile). - - -### Step 3: Set Up Your Development Environment - -Make sure your system meets these requirements: - -- Node.js installed -- A code editor like [Visual Studio Code](https://code.visualstudio.com/) or [Cursor](https://www.cursor.com/) -- npm, pnpm, or Yarn - -*** - -## Built With - -The Astro integration relies on the following technologies: - -| Technology | Description | -| --- | --- | -| [Node.js](https://nodejs.org/) | JavaScript runtime environment | -| [npm](https://www.npmjs.com/) | Package manager | -| [Astro](https://astro.build/) | Web framework for content-focused sites | -| [@astrojs/react](https://docs.astro.build/en/guides/integrations-guide/react/) | Optional: React integration for using CometChat React UI Kit | - -*** +1. App ID +2. Auth Key +3. Region ## Getting Started -### Step 1: Create an Astro Project + + - ```bash + ```bash lines npm create astro@latest cd npm install ``` - ```bash + ```bash lines pnpm create astro@latest my-astro-app --template basics cd pnpm install ``` - ```bash + ```bash lines yarn create astro my-astro-app --template basics cd yarn @@ -111,30 +59,25 @@ The Astro integration relies on the following technologies: - Prefer SSR or hybrid rendering? Astro supports islands and client hydration. CometChat’s UI and SDK must run on the client. +CometChat UI and SDK must run on the client. Use `client:only="react"` for Astro islands. -*** - -### Step 2: Install Dependencies + -Choose one of the following: - -- JavaScript SDK only (maximum control) -- React UI Kit (prebuilt UI) with Astro’s React integration + - ```bash + ```bash lines npm i @cometchat/chat-uikit-react ``` - ```bash + ```bash lines npx astro add react ``` - After installing, ensure the React integration exists in `astro.config.mjs`: - ```js + Ensure the React integration exists in `astro.config.mjs`: + ```js lines import { defineConfig } from 'astro/config' import react from '@astrojs/react' @@ -146,7 +89,7 @@ Choose one of the following: - Create a `.env` file at the project root and add the following environment variables used by the examples: + Create a `.env` file at the project root: ```bash PUBLIC_COMETCHAT_APP_ID=your_app_id @@ -158,11 +101,11 @@ Choose one of the following: ``` -*** + -### Step 3: Initialize CometChat (UI Kit) + -Use a shared initializer that reads from environment variables and initializes the React UI Kit. This pattern matches the example projects. +Shared initializer that reads from environment variables: ```js // src/lib/cometchat-init.js @@ -200,144 +143,85 @@ export async function ensureLogin(uid) { ``` - Replace placeholders with your actual CometChat credentials before testing. +Replace placeholders with actual CometChat credentials before testing. -*** + -### Step 4: User Login + -The example islands handle login automatically using `ensureLogin(uid)` from `src/lib/cometchat-init.js`. Configure `PUBLIC_COMETCHAT_LOGIN_UID` (and `PUBLIC_COMETCHAT_TARGET_UID` for one-to-one) in your `.env`. +The example islands handle login automatically using `ensureLogin(uid)` from `src/lib/cometchat-init.js`. Configure `PUBLIC_COMETCHAT_LOGIN_UID` (and `PUBLIC_COMETCHAT_TARGET_UID` for one-to-one) in `.env`. - Security Best Practices - - - Auth Key is suitable for POCs and early testing. - - In production, prefer an Auth Token issued by your backend. +Auth Key is for development/POC only. Use [Auth Token](/ui-kit/react/methods#login-using-auth-token) in production. - Test UIDs you can use immediately: `cometchat-uid-1`, `cometchat-uid-2`, `cometchat-uid-3`, `cometchat-uid-4`, `cometchat-uid-5`. +Test UIDs: `cometchat-uid-1` through `cometchat-uid-5`. -*** - -### **Step 5: Choose a Chat Experience** + -Integrate a conversation view that suits your application's **UX requirements**. Below are the available options: + -*** +Three layout options: -#### **1️⃣ Conversation List + Message View** +#### Conversation List + Message View -**Best for:** Applications that need a **two-panel layout**, such as web-based chat interfaces (e.g., WhatsApp Web, Slack). - -**Features:** - -* **Two-panel layout** – Displays the conversation list on the left and the active chat window on the right. -* **One-to-one & group conversations** – Seamless switching between private and group chats. -* **Multiple conversations** – Effortlessly switch between different chat windows. -* **Easy navigation** – Intuitive UI for finding and accessing chats quickly. -* **Tap-to-view on mobile** – In mobile layouts, tapping a conversation opens the **Message View**, optimizing space. -* **Real-time updates** – Auto-refreshes messages and conversation lists. -* **Message sync** – Ensures messages stay updated across all sessions and devices. +Two-panel layout: conversation list on the left, active chat on the right. Supports 1:1 and group conversations with real-time updates. - + -**Recommended for:** - -* Desktop-first applications -* Apps requiring a **rich user experience** with seamless navigation -* Platforms supporting both **individual and group messaging** -* **Mobile-friendly** apps needing a **tap-to-open message view** - [Integrate Conversation List + Message](./astro-conversation) -*** - -#### **2️⃣ One-to-One/Group Chat** - -**Best for:** Apps that require a **focused, direct messaging experience** without a sidebar. +#### One-to-One/Group Chat -**Features:** - -* **Dedicated chat window** – Ideal for one-on-one or group messaging. -* **No conversation list** – Users directly enter the chat without navigating through a list. -* **Supports both One-to-One and Group Chats** – Easily configurable with minor code modifications. -* **Optimized for mobile** – Full-screen chat experience without distractions. -* **Seamless real-time communication** – Auto-updates messages for a smooth experience. -* **Ideal for support chat or community-based messaging.** +Single chat window without a conversation list. Supports both 1:1 and group messaging. - + -**Recommended for:** - -* **Support chat applications** – Direct user-agent communication. -* **Apps focusing on direct messaging** – No distractions from other conversations. -* **Community or group chat applications** – A structured way to interact in groups. -* **Mobile-first applications** – Designed for compact and dedicated messaging experiences. - [Integrate One-to-One/Group Chat](./astro-one-to-one-chat) -*** +#### Tab-Based Chat Experience -#### **3️⃣ Tab-Based Chat Experience** - -**Best for:** Apps that need a **structured, multi-feature navigation system** for seamless interaction between **chats, calls, users, and settings**. - -**Features:** - -* **Tab Navigation** – Easily switch between **Chat, Call Logs, Users, and Settings**. -* **Dedicated Chat Window** – Full-screen messaging experience for focused communication. -* **No Sidebar** – Unlike multi-panel UI, this design prioritizes individual interactions. -* **Unified Experience** – Users can seamlessly manage conversations, call history, and settings from a single interface. -* **Scalable for future features** – Easily extend to include more functionalities such as notifications or contact management. -* **Optimized for both desktop and mobile** – Ensures a smooth experience across different screen sizes. +Tab navigation between Chat, Call Logs, Users, and Settings. Works across desktop and mobile. - + -**Recommended for:** - -* **Apps requiring structured navigation** – Clearly separate chat, calls, and settings. -* **Multi-feature chat apps** – Supporting different functionalities in an organized way. -* **Mobile-first applications** – Ideal for apps needing tab-based UI for easy access to features. -* **Support & enterprise chat solutions** – Perfect for help desks, business chat platforms, and customer support apps. - [Integrate Tab-Based Chat](./astro-tab-based-chat) -*** + + ## Build Your Own Chat Experience -If you need full control, combine the JavaScript SDK with your own UI or mix Astro islands with select UI Kit components. Customize themes, behaviors, and data flows as needed. - -**Key Areas to Explore:** +For full control over the chat interface, use individual components directly: - [React Sample App](https://github.com/cometchat/cometchat-uikit-react/tree/v6/sample-app) - [Core Features](./core-features) - [Components](./components-overview) - [Themes](./theme) -- [Build Your Own UI](./../../../sdk/javascript/overview) - -*** +- [Build with SDK](./../../../sdk/javascript/overview) ## Next Steps -Proceed with your chosen experience: - -- Conversation + Messages (UI Kit) in Astro using `CometChatConversationsWithMessages` -- One-to-One/Group Messages (UI Kit) in Astro using `CometChatMessages` -- Tab-Based Chat (UI Kit) in Astro using `CometChatFullScreenView` -- Advanced customizations with themes and components - - - You’ve set up CometChat in your Astro app. Initialize, log in, and render your preferred chat experience. - - - + + + Two-panel layout with conversation list and message view. + + + Focused direct messaging experience without a sidebar. + + + Multi-tab navigation for chats, calls, users, and settings. + + + Customize colors, fonts, and styles. + + diff --git a/ui-kit/react/astro-one-to-one-chat.mdx b/ui-kit/react/astro-one-to-one-chat.mdx index 54addcac0..74444385c 100644 --- a/ui-kit/react/astro-one-to-one-chat.mdx +++ b/ui-kit/react/astro-one-to-one-chat.mdx @@ -1,11 +1,19 @@ --- title: "Building a One-to-One/Group Chat in Astro" sidebarTitle: "One To One/Group Chat" +description: "Build a focused one-to-one or group chat experience in Astro with CometChat React UI Kit." --- -The One‑to‑One/Group chat layout focuses on a single conversation, ideal for support chats and private messaging. This guide uses Astro with React islands and the CometChat React UI Kit. + +- **Package:** `@cometchat/chat-uikit-react` +- **Framework:** Astro (with `@astrojs/react` islands) +- **Key component:** `CometChatMessages` +- **Required setup:** `CometChatUIKit.init(UIKitSettings)` then `CometChatUIKit.login("UID")` — use `client:only="react"` directive +- **Parent guide:** [Astro Integration](/ui-kit/react/astro-integration) + + -*** +The One‑to‑One/Group chat layout focuses on a single conversation, ideal for support chats and private messaging. This guide uses Astro with React islands and the CometChat React UI Kit. ## User Interface Preview @@ -15,11 +23,9 @@ The One‑to‑One/Group chat layout focuses on a single conversation, ideal for **Key Components** -1. Chat Header – recipient details and status -2. Message View – history and live messages -3. Message Composer – text, media, attachments - -*** +1. Chat Header — recipient details and status +2. Message View — history and live messages +3. Message Composer — text, media, attachments ## Prerequisites @@ -211,9 +217,25 @@ The One‑to‑One/Group chat layout focuses on a single conversation, ideal for - ```bash - npm run dev - ``` + + + ```bash lines + npm run dev + ``` + + + + ```bash lines + pnpm dev + ``` + + + + ```bash lines + yarn dev + ``` + + Set `PUBLIC_COMETCHAT_LOGIN_UID` and `PUBLIC_COMETCHAT_TARGET_UID` then verify messages appear for the selected peer. @@ -221,8 +243,6 @@ The One‑to‑One/Group chat layout focuses on a single conversation, ideal for -*** - ## Switch to Group Chat To load a group instead of a user, fetch it with the SDK and pass it to the UI Kit components. @@ -237,8 +257,6 @@ const group = await CometChat.getGroup("YOUR_GROUP_ID"); When switching between user and group, keep only one of `user` or `group` props set at a time. -*** - ## Troubleshooting @@ -255,16 +273,22 @@ The island logs out if a different user session is active, then logs in with `PU -*** +For prop details and customization options, see the component reference pages: [CometChatConversations](/ui-kit/react/conversations), [CometChatMessageList](/ui-kit/react/message-list), [CometChatMessageComposer](/ui-kit/react/message-composer), [CometChatMessageHeader](/ui-kit/react/message-header). ## Next Steps -- Add typing indicators and read receipts -- Apply theming and component overrides -- Extend to conversations list + messages or tabbed layout + + + Browse all available UI components. + + + Astro setup guide. + + + Core chat features. + + You can reuse `src/lib/cometchat-init.js` across different chat experiences and swap the island component. - - diff --git a/ui-kit/react/astro-tab-based-chat.mdx b/ui-kit/react/astro-tab-based-chat.mdx index cf532ef4f..2ec4721fb 100644 --- a/ui-kit/react/astro-tab-based-chat.mdx +++ b/ui-kit/react/astro-tab-based-chat.mdx @@ -1,11 +1,19 @@ --- title: "Building a Messaging UI with Tabs, Sidebar, and Message View in Astro" sidebarTitle: "Tab Based Chat Experience" +description: "Build a tab-based messaging UI with chats, calls, users, and groups in Astro with CometChat React UI Kit." --- -This guide shows how to build a tab‑based messaging UI in Astro using the CometChat React UI Kit. The interface includes sections for Chats, Calls, Users, and Groups with a message panel. + +- **Package:** `@cometchat/chat-uikit-react` +- **Framework:** Astro (with `@astrojs/react` islands) +- **Key component:** `CometChatFullScreenView` +- **Required setup:** `CometChatUIKit.init(UIKitSettings)` then `CometChatUIKit.login("UID")` — use `client:only="react"` directive +- **Parent guide:** [Astro Integration](/ui-kit/react/astro-integration) + + -*** +This guide shows how to build a tab‑based messaging UI in Astro using the CometChat React UI Kit. The interface includes sections for Chats, Calls, Users, and Groups with a message panel. ## User Interface Preview @@ -15,11 +23,9 @@ This guide shows how to build a tab‑based messaging UI in Astro using the Come Layout structure: -1. Sidebar – conversations, users, groups, or call logs -2. Messages – header, list, and composer -3. Tabs – switch between Chats, Calls, Users, and Groups - -*** +1. Sidebar — conversations, users, groups, or call logs +2. Messages — header, list, and composer +3. Tabs — switch between Chats, Calls, Users, and Groups ## Prerequisites @@ -230,7 +236,7 @@ Layout structure: setSelectedUser(null); setActiveTab("chats"); // show messages in same area } else { - // For calls tab, we don’t open message panel + // For calls tab, we don't open message panel setSelectedUser(null); setSelectedGroup(null); } @@ -325,9 +331,25 @@ Layout structure: - ```bash - npm run dev - ``` + + + ```bash lines + npm run dev + ``` + + + + ```bash lines + pnpm dev + ``` + + + + ```bash lines + yarn dev + ``` + + Log in using `PUBLIC_COMETCHAT_LOGIN_UID`, switch tabs, and open a conversation to send messages. @@ -335,8 +357,6 @@ Layout structure: -*** - ## Troubleshooting @@ -353,16 +373,18 @@ The message panel shows only for Chats, Users, or Groups. Calls tab does not ope -*** +For prop details and customization options, see the component reference pages: [CometChatConversations](/ui-kit/react/conversations), [CometChatMessageList](/ui-kit/react/message-list), [CometChatMessageComposer](/ui-kit/react/message-composer), [CometChatMessageHeader](/ui-kit/react/message-header). ## Next Steps - -- Add call handling with CometChat Calls SDK -- Apply theming and component overrides -- Extend with unread badges and notifications - - -You can reuse `src/lib/cometchat-init.js` and swap the island component to build other experiences. - - + + + Browse all available UI components. + + + Astro setup guide. + + + Core chat features. + + diff --git a/ui-kit/react/call-buttons.mdx b/ui-kit/react/call-buttons.mdx index 4c67d12bb..a19f7dfdf 100644 --- a/ui-kit/react/call-buttons.mdx +++ b/ui-kit/react/call-buttons.mdx @@ -1,409 +1,537 @@ --- title: "Call Buttons" +description: "Voice and video call initiation buttons for user or group conversations." --- + +```json +{ + "component": "CometChatCallButtons", + "package": "@cometchat/chat-uikit-react", + "import": "import { CometChatCallButtons } from \"@cometchat/chat-uikit-react\";", + "cssImport": "import \"@cometchat/chat-uikit-react/css-variables.css\";", + "description": "Voice and video call initiation buttons for user or group conversations.", + "cssRootClass": ".cometchat-call-button", + "primaryOutput": { + "description": "Initiates calls via SDK, emits CometChatCallEvents" + }, + "props": { + "data": { + "user": { + "type": "CometChat.User", + "default": "undefined", + "note": "Pass either user or group, not both" + }, + "group": { + "type": "CometChat.Group", + "default": "undefined", + "note": "Pass either user or group, not both" + } + }, + "callbacks": { + "onError": "((error: CometChat.CometChatException) => void) | null", + "onVoiceCallClick": "(user?: CometChat.User, group?: CometChat.Group) => void", + "onVideoCallClick": "(user?: CometChat.User, group?: CometChat.Group) => void" + }, + "visibility": { + "hideVoiceCallButton": { "type": "boolean", "default": false }, + "hideVideoCallButton": { "type": "boolean", "default": false } + }, + "configuration": { + "callSettingsBuilder": "(isAudioOnlyCall: boolean, user?: CometChat.User, group?: CometChat.Group) => typeof CometChatUIKitCalls.CallSettingsBuilder", + "outgoingCallConfiguration": { + "type": "OutgoingCallConfiguration", + "default": "new OutgoingCallConfiguration({})", + "properties": { + "disableSoundForCalls": "boolean", + "customSoundForCalls": "string", + "onError": "(error: CometChat.CometChatException) => void", + "onCallCanceled": "Function", + "titleView": "(call: CometChat.Call) => JSX.Element", + "subtitleView": "(call: CometChat.Call) => JSX.Element", + "avatarView": "(call: CometChat.Call) => JSX.Element", + "cancelButtonView": "(call: CometChat.Call) => JSX.Element" + } + } + } + }, + "events": [ + { + "name": "CometChatCallEvents.ccOutgoingCall", + "payload": "CometChat.Call", + "description": "Call initiated" + }, + { + "name": "CometChatCallEvents.ccCallRejected", + "payload": "CometChat.Call", + "description": "Call rejected/cancelled" + }, + { + "name": "CometChatCallEvents.ccCallEnded", + "payload": "CometChat.Call", + "description": "Call session ends" + }, + { + "name": "CometChatMessageEvents.ccMessageSent", + "payload": "IMessages", + "description": "Group call message sent" + } + ], + "sdkListeners": [ + "onIncomingCallReceived", + "onIncomingCallCancelled", + "onOutgoingCallRejected", + "onOutgoingCallAccepted" + ], + "compositionExample": { + "description": "Standalone call buttons or embedded in MessageHeader auxiliary view", + "components": ["CometChatCallButtons", "CometChatOutgoingCall", "CometChatOngoingCall"], + "flow": "user/group prop -> click button -> SDK initiateCall -> CometChatOutgoingCall overlay -> onOutgoingCallAccepted -> CometChatOngoingCall" + } +} +``` + -## Overview - -The `Call Button` is a Component provides users with the ability to make calls, access call-related functionalities, and control call settings. Clicking this button typically triggers the call to be placed to the desired recipient. - - - - - -## Usage +## Where It Fits -### Integration +`CometChatCallButtons` renders voice and video call buttons. Pass a `user` for 1-on-1 calls or a `group` for group calls. Typically embedded in `CometChatMessageHeader`'s auxiliary view or used standalone. The component handles call initiation, renders `CometChatOutgoingCall` internally, and manages the full call lifecycle. - - ```tsx +import { useState, useEffect } from "react"; import { CometChat } from "@cometchat/chat-sdk-javascript"; import { CometChatCallButtons } from "@cometchat/chat-uikit-react"; -import React from "react"; - -const CallButtonDemo = () => { - const [chatUser, setChatUser] = React.useState(); - React.useEffect(() => { - CometChat.getUser("uid").then((user) => { - setChatUser(user); - }); - }, []); - return ; -}; +import "@cometchat/chat-uikit-react/css-variables.css"; -export default CallButtonDemo; -``` - - +function CallButtonsDemo() { + const [chatUser, setChatUser] = useState(); - -```tsx -import { CallButtonDemo } from "./CallButtonDemo"; + useEffect(() => { + CometChat.getUser("uid").then((user) => setChatUser(user)); + }, []); -export default function App() { - return ( -
-
- -
-
- ); + return chatUser ? : null; } -``` - -
-
- -### Actions +export default CallButtonsDemo; +``` -[Actions](/ui-kit/react/components-overview#actions) dictate how a component functions. They are divided into two types: Predefined and User-defined. You can override either type, allowing you to tailor the behavior of the component to fit your specific needs. + + + -##### 1. onError +--- -This action doesn't change the behavior of the component but rather listens for any errors that occur in the Call Button component. +## Minimal Render - - -```ts -import { CometChat } from "@cometchat/chat-sdk-javascript"; +```tsx import { CometChatCallButtons } from "@cometchat/chat-uikit-react"; -import React from "react"; - -const CallButtonDemo = () => { - const [chatUser, setChatUser] = React.useState(); - React.useEffect(() => { - CometChat.getUser("uid").then((user) => { - setChatUser(user); - }); - }, []); - - const handleOnError = (error: CometChat.CometChatException) => { - console.log("Your Custom on error actions", error); - }; - - return ; -}; +import "@cometchat/chat-uikit-react/css-variables.css"; -export default CallButtonDemo; +function CallButtonsMinimal() { + return ; +} ``` - - - -```js -import React, { useState, useEffect } from "react"; -import { CometChat } from "@cometchat/chat-sdk-javascript"; -import { CometChatCallButtons } from "@cometchat/chat-uikit-react"; - -const CallButtonDemo = () => { - const [chatUser, setChatUser] = useState(null); - - useEffect(() => { - CometChat.getUser("uid").then((user) => { - setChatUser(user); - }); - }, []); - - const handleOnError = (error) => { - console.log("Your Custom on error actions", error); - }; - - return ; -}; - -export default CallButtonDemo; -``` +Root CSS class: `.cometchat-call-button` - +--- - +## Actions and Events -*** +### Callback Props -### Filters +#### onVoiceCallClick -You can set `CallSettingsBuilder` in the Call Buttons Component to customise the calling experience. To know more about the filters available please refer to [CallSettingsBuilder](/sdk/javascript/direct-call#settings). +Overrides the default voice call initiation behavior. When set, clicking the voice button invokes this callback instead of initiating a call via the SDK. - - -```ts +```tsx +import { useState, useEffect } from "react"; import { CometChat } from "@cometchat/chat-sdk-javascript"; import { CometChatCallButtons } from "@cometchat/chat-uikit-react"; -import React from "react"; -const CallButtonDemo = () => { - const [chatUser, setChatUser] = React.useState(); +function CallButtonsVoiceOverride() { + const [chatUser, setChatUser] = useState(); - React.useEffect(() => { - CometChat.getUser("uid").then((user) => { - setChatUser(user); - }); + useEffect(() => { + CometChat.getUser("uid").then((user) => setChatUser(user)); }, []); - const getCallSettingsBuilder = (call: CometChat.Call) => { - return new CometChatCalls.CallSettingsBuilder() - .setIsAudioOnlyCall( - call?.getType() === CometChatUIKitConstants.MessageTypes.audio - ? true - : false - ) - .build(); - }; - return ( { + console.log("Custom voice call logic"); + }} /> ); -}; - -export default CallButtonDemo; +} ``` - +#### onVideoCallClick + +Overrides the default video call initiation behavior. - -```js -import React, { useState, useEffect } from "react"; +```tsx +import { useState, useEffect } from "react"; import { CometChat } from "@cometchat/chat-sdk-javascript"; import { CometChatCallButtons } from "@cometchat/chat-uikit-react"; -const CallButtonDemo = () => { - const [chatUser, setChatUser] = useState(null); +function CallButtonsVideoOverride() { + const [chatUser, setChatUser] = useState(); useEffect(() => { - CometChat.getUser("uid").then((user) => { - setChatUser(user); - }); + CometChat.getUser("uid").then((user) => setChatUser(user)); }, []); - const getCallSettingsBuilder = (call) => { - return new CometChatCalls.CallSettingsBuilder() - .setIsAudioOnlyCall( - call?.getType() === CometChatUIKitConstants.MessageTypes.audio - ? true - : false - ) - .build(); - }; - return ( { + console.log("Custom video call logic"); + }} /> ); -}; - -export default CallButtonDemo; +} ``` - - - +#### onError -*** +Fires on internal errors during call initiation. -### Events +```tsx +import { CometChatCallButtons } from "@cometchat/chat-uikit-react"; +import { CometChat } from "@cometchat/chat-sdk-javascript"; -[Events](/ui-kit/react/components-overview#events) are emitted by a `Component`. By using event you can extend existing functionality. Being global events, they can be applied in Multiple Locations and are capable of being Added or Removed. +function CallButtonsWithError() { + return ( + { + console.error("CallButtons error:", error); + }} + /> + ); +} +``` -The list of events emitted by the `Call Buttons` component is as follows. +### Global UI Events -| Event | Description | -| ------------------ | --------------------------------------------------------------------------------------------------------- | -| **ccCallRejected** | This event is triggered when the initiated call is rejected by the receiver. | -| **ccCallEnded** | This event is triggered when the initiated call successfully ends. | -| **ccOutgoingCall** | This event is triggered when the user initiates a voice/video call. | -| **ccMessageSent** | This event is triggered when the sent message is in transit and also when it is received by the receiver. | +`CometChatCallEvents` emits call lifecycle events subscribable from anywhere. -*** +| Event | Fires when | Payload | +| --- | --- | --- | +| `ccOutgoingCall` | User initiates a voice/video call | `CometChat.Call` | +| `ccCallRejected` | Initiated call is rejected/cancelled | `CometChat.Call` | +| `ccCallEnded` | Call session ends | `CometChat.Call` | - - ```tsx -const ccCallRejected = CometChatCallEvents.ccCallRejected.subscribe( - (call: CometChat.Call) => { - //Your Code - } -); +import { useEffect } from "react"; +import { CometChatCallEvents } from "@cometchat/chat-uikit-react"; +import { CometChat } from "@cometchat/chat-sdk-javascript"; -const ccCallEnded = CometChatCallEvents.ccCallEnded.subscribe( - (call: CometChat.Call) => { - //Your Code - } -); +function useCallButtonEvents() { + useEffect(() => { + const outgoingSub = CometChatCallEvents.ccOutgoingCall.subscribe( + (call: CometChat.Call) => { + console.log("Outgoing call:", call.getSessionId()); + } + ); + const rejectedSub = CometChatCallEvents.ccCallRejected.subscribe( + (call: CometChat.Call) => { + console.log("Call rejected:", call.getSessionId()); + } + ); + const endedSub = CometChatCallEvents.ccCallEnded.subscribe( + (call: CometChat.Call) => { + console.log("Call ended:", call.getSessionId()); + } + ); + + return () => { + outgoingSub?.unsubscribe(); + rejectedSub?.unsubscribe(); + endedSub?.unsubscribe(); + }; + }, []); +} +``` -const ccOutgoingCall = CometChatCallEvents.ccOutgoingCall.subscribe( - (call: CometChat.Call) => { - //Your Code - } -); +### SDK Events (Real-Time, Automatic) -const ccMessageSent = CometChatMessageEvents.ccMessageSent.subscribe(() => { - //Your Code -}); -``` +The component attaches SDK call listeners internally: - +| SDK Listener | Internal behavior | +| --- | --- | +| `onIncomingCallReceived` | Disables call buttons to prevent concurrent calls | +| `onIncomingCallCancelled` | Re-enables call buttons | +| `onOutgoingCallRejected` | Hides outgoing call screen, re-enables buttons | +| `onOutgoingCallAccepted` | Transitions to ongoing call screen | - +--- -*** +## Configuring the Outgoing Call Sub-Component + +`CometChatCallButtons` renders `CometChatOutgoingCall` internally. Customize it via `outgoingCallConfiguration`. - - ```tsx -ccCallRejected?.unsubscribe(); +import { CometChatCallButtons, OutgoingCallConfiguration } from "@cometchat/chat-uikit-react"; -ccCallEnded?.unsubscribe(); +function CallButtonsCustomOutgoing() { + return ( +
{call.getCallReceiver().getName()}
, + }) + } + /> + ); +} +``` -ccOutgoingCall?.unsubscribe(); +`OutgoingCallConfiguration` properties: -ccMessageSent?.unsubscribe(); -``` +| Property | Type | Description | +| --- | --- | --- | +| `disableSoundForCalls` | `boolean` | Disables outgoing call ringtone | +| `customSoundForCalls` | `string` | Custom ringtone URL | +| `onError` | `(error: CometChat.CometChatException) => void` | Error callback | +| `onCallCanceled` | `Function` | Cancel button callback | +| `titleView` | `(call: CometChat.Call) => JSX.Element` | Custom title | +| `subtitleView` | `(call: CometChat.Call) => JSX.Element` | Custom subtitle | +| `avatarView` | `(call: CometChat.Call) => JSX.Element` | Custom avatar | +| `cancelButtonView` | `(call: CometChat.Call) => JSX.Element` | Custom cancel button | -
+Refer to [CometChatOutgoingCall](/ui-kit/react/outgoing-call) for details on each view slot. -
+--- -*** +## Call Settings -## Customization +Customize the calling experience via `callSettingsBuilder`. -To fit your app's design requirements, you can customize the appearance of the Call Buttons component. We provide exposed methods that allow you to modify the experience and behavior according to your specific needs. +```tsx +import { CometChat } from "@cometchat/chat-sdk-javascript"; +import { CometChatCallButtons, CometChatUIKitCalls } from "@cometchat/chat-uikit-react"; -### Style +function CallButtonsCustomSettings() { + return ( + + new CometChatUIKitCalls.CallSettingsBuilder() + .enableDefaultLayout(true) + .setIsAudioOnlyCall(isAudioOnlyCall) + } + /> + ); +} +``` -Using CSS you can customize the look and feel of the component in your app like the color, size, shape, and fonts. +--- - - - +## Common Patterns -**Example** +### Voice-only call button - - -```ts -import { CometChat } from "@cometchat/chat-sdk-javascript"; +```tsx import { CometChatCallButtons } from "@cometchat/chat-uikit-react"; -import React from "react"; - -const CallButtonDemo = () => { - const [chatUser, setChatUser] = React.useState(); - React.useEffect(() => { - CometChat.getUser("uid").then((user) => { - setChatUser(user); - }); - }, []); - return ; -}; - -export default CallButtonDemo; +function VoiceOnlyCallButtons() { + return ; +} ``` - +### Group call buttons - -```js -import React, { useState, useEffect } from "react"; +```tsx +import { useState, useEffect } from "react"; import { CometChat } from "@cometchat/chat-sdk-javascript"; import { CometChatCallButtons } from "@cometchat/chat-uikit-react"; -const CallButtonDemo = () => { - const [chatUser, setChatUser] = useState(null); +function GroupCallButtons() { + const [group, setGroup] = useState(); useEffect(() => { - CometChat.getUser("uid").then((user) => { - setChatUser(user); - }); + CometChat.getGroup("guid").then((g) => setGroup(g)); }, []); - return ; -}; - -export default CallButtonDemo; + return group ? : null; +} ``` - +--- + +## CSS Architecture + +The component uses CSS custom properties (design tokens) defined in `@cometchat/chat-uikit-react/css-variables.css`. The cascade: + +1. Global tokens set on the `.cometchat` root wrapper. +2. Component CSS (`.cometchat-call-button`) consumes these tokens via `var()`. +3. Overrides target `.cometchat-call-button` descendant selectors. + +### Key Selectors + +| Target | Selector | +| --- | --- | +| Root | `.cometchat-call-button` | +| Voice button wrapper | `.cometchat-call-button__voice` | +| Video button wrapper | `.cometchat-call-button__video` | +| Button element | `.cometchat-call-button .cometchat-button` | +| Button icon | `.cometchat-call-button .cometchat-button__icon` | +| Outgoing call backdrop | `.cometchat-outgoing-call__backdrop` | + +### Example: Themed call buttons + + + + - ```css .cometchat-call-button { display: flex; - width: 183px; - height: 64px; padding: 8px 16px; justify-content: center; align-items: center; - border-bottom: 1px solid #f5f5f5; background: #fff; } -.cometchat-call-button .cometchat-call-button__voice, -.cometchat-call-button .cometchat-call-button__video { - width: auto; - height: auto; -} - .cometchat .cometchat-button { - display: flex; - width: 52px; - height: 40px; - justify-content: center; - padding: 8px 20px; - align-items: center; border-radius: 8px; border: 1px solid #e8e8e8; background: #edeafa; } -.cometchat .cometchat-button:hover { - background-color: #edeafa; -} - .cometchat-call-button .cometchat-call-button__video .cometchat-button__icon, .cometchat-call-button .cometchat-call-button__voice .cometchat-button__icon { - width: 24px; - height: 24px; - flex-shrink: 0; background-color: #6852d6; } ``` - +### Customization Matrix + +| What to change | Where | Property/API | Example | +| --- | --- | --- | --- | +| Override call initiation | Component props | `onVoiceCallClick` / `onVideoCallClick` | `onVoiceCallClick={() => customCall()}` | +| Hide a call button | Component props | `hideVoiceCallButton` / `hideVideoCallButton` | `hideVideoCallButton={true}` | +| Customize outgoing call UI | Component props | `outgoingCallConfiguration` | `outgoingCallConfiguration={new OutgoingCallConfiguration({...})}` | +| Customize call settings | Component props | `callSettingsBuilder` | `callSettingsBuilder={(audio) => builder}` | +| Change colors, fonts, spacing | Global CSS | Target `.cometchat-call-button` class | `.cometchat-call-button .cometchat-button__icon { background: red; }` | + +--- + +## Accessibility + +The voice and video call buttons are keyboard-focusable and activate on Enter/Space. Each button includes hover text ("Voice Call" / "Video Call") for tooltip display. Buttons are disabled during active calls to prevent concurrent call initiation. + +--- + +--- + +## Props + +All props are optional. Sorted alphabetically. + +### callSettingsBuilder + +Builder function for customizing call settings. - +| | | +| --- | --- | +| Type | `(isAudioOnlyCall: boolean, user?: CometChat.User, group?: CometChat.Group) => typeof CometChatUIKitCalls.CallSettingsBuilder` | +| Default | `undefined` | -*** +--- + +### group + +The group for group call buttons. Pass either `user` or `group`, not both. -## Configurations +| | | +| --- | --- | +| Type | `CometChat.Group` | +| Default | `undefined` | -Configurations offer the ability to customize the properties of each component within a Composite Component. `CallButtons` component renders [CometChatOutgoingCall](/ui-kit/react/outgoing-call) component. +--- + +### hideVideoCallButton -#### Outgoing Call +Hides the video call button. -You can customize the properties of the `CometChatOutgoingCall` component by making use of the `OutgoingCallConfiguration`. Below properties are available in `OutgoingCallConfiguration`. +| | | +| --- | --- | +| Type | `boolean` | +| Default | `false` | -| Property | Description | Code | -| -------------------------- | ------------------------------------------------------------------------------- | ---------------------------------------------------------------------------------- | -| **User** | Sets the user object for Call Buttons | `user={chatUser}` | -| **Group** | Used to set the group object for Call Buttons | `group={chatGroup}` | -| **Custom Sound** | Specifies a custom sound to play for outgoing calls. | `customSoundForCalls='Your Custom Sound For Calls'` | -| **Disable Sound** | Disables the sound of outgoing calls. | `disableSoundForCalls={false}` | -| **On Error** | Callback function triggered when an error occurs in the call buttons component. | `onError={(error: CometChat.CometChatException)=>{ console.log('error', error) }}` | -| **Cancel Call Clicked** | Callback function triggered when the cancel button is clicked. | `onCloseClicked={()=>{console.log("Outgoing call canceled")}}` | -| **Title View** | This prop renders the custom title view for the outgoing call. | `titleView={<>Custom Title View}` | -| **Sub Title View** | This prop renders the custom sub title view for the outgoing call. | `subtitleView={<>Custom Sub Title View}` | -| **Avatar View** | This prop renders the custom avatar view for the outgoing call. | `avatarView={<>Custom Avatar View}` | -| **Cancel Button View** | This prop renders the custom cancel-call button view for the outgoing call. | `cancelButtonView={<>Custom Cancel Button View}` | -| **Hide Video Call Button** | Used to hide the video call button. | `hideVideoCallButton={true}` | -| **Hide Voice Call Button** | Used to hide the voice call button. | `hideVoiceCallButton={true}` | +--- + +### hideVoiceCallButton + +Hides the voice call button. + +| | | +| --- | --- | +| Type | `boolean` | +| Default | `false` | + +--- + +### onError + +Callback fired when the component encounters an error. + +| | | +| --- | --- | +| Type | `((error: CometChat.CometChatException) => void) \| null` | +| Default | `undefined` | + +--- + +### outgoingCallConfiguration + +Configuration object for the internal `CometChatOutgoingCall` sub-component. + +| | | +| --- | --- | +| Type | `OutgoingCallConfiguration` | +| Default | `new OutgoingCallConfiguration({})` | + +See [Configuring the Outgoing Call Sub-Component](#configuring-the-outgoing-call-sub-component) for properties. + +--- + +### user + +The user for 1-on-1 call buttons. Pass either `user` or `group`, not both. + +| | | +| --- | --- | +| Type | `CometChat.User` | +| Default | `undefined` | + +--- + +## Events + +| Event | Payload | Fires when | +| --- | --- | --- | +| `CometChatCallEvents.ccOutgoingCall` | `CometChat.Call` | Call initiated | +| `CometChatCallEvents.ccCallRejected` | `CometChat.Call` | Call rejected/cancelled | +| `CometChatCallEvents.ccCallEnded` | `CometChat.Call` | Call session ends | +| `CometChatMessageEvents.ccMessageSent` | `IMessages` | Group call message sent | + +All call events are `Subject` from RxJS. Subscribe with `.subscribe()`, unsubscribe with the returned subscription's `.unsubscribe()`. + +--- -You can refer to [CometChatOutgoingCall](/ui-kit/react/outgoing-call) component to know more about each of the above properties. +## CSS Selectors -*** +| Target | Selector | +| --- | --- | +| Root | `.cometchat-call-button` | +| Voice button wrapper | `.cometchat-call-button__voice` | +| Video button wrapper | `.cometchat-call-button__video` | +| Button element | `.cometchat-call-button .cometchat-button` | +| Button icon | `.cometchat-call-button .cometchat-button__icon` | +| Outgoing call backdrop | `.cometchat-outgoing-call__backdrop` | diff --git a/ui-kit/react/call-features.mdx b/ui-kit/react/call-features.mdx index f9d61886a..3cbac633a 100644 --- a/ui-kit/react/call-features.mdx +++ b/ui-kit/react/call-features.mdx @@ -1,24 +1,34 @@ --- title: "Call" +description: "Overview of CometChat's audio and video calling features including incoming calls, outgoing calls, and call logs — with the UI Kit components that power each feature." --- -## Overview + +- **Packages:** `@cometchat/chat-uikit-react` + `@cometchat/calls-sdk-javascript` (`npm install @cometchat/calls-sdk-javascript`) +- **Required setup:** `CometChatUIKit.init(UIKitSettings)` then `CometChatUIKit.login("UID")` — Calls SDK must also be installed +- **Call features:** Incoming Call, Outgoing Call, Call Logs, Call Buttons +- **Key components:** `CometChatCallButtons` → [Call Buttons](/ui-kit/react/call-buttons), `CometChatIncomingCall` → [Incoming Call](/ui-kit/react/incoming-call), `CometChatOutgoingCall` → [Outgoing Call](/ui-kit/react/outgoing-call), `CometChatCallLogs` → [Call Logs](/ui-kit/react/call-logs) +- **Auto-detection:** UI Kit automatically detects the Calls SDK and enables call UI components +- **CSS class prefix:** `.cometchat-` + -CometChat's Calls feature is an advanced functionality that allows you to seamlessly integrate one-on-one as well as group audio and video calling capabilities into your application. This document provides a technical overview of these features, as implemented in the React UI Kit. +## Overview -## Integration +CometChat Calls integrates 1:1 and group audio/video calling into the React UI Kit. Install the Calls SDK and the UI Kit auto-detects it, enabling call components. -First, make sure that you've correctly integrated the UI Kit library into your project. If you haven't done this yet or are facing difficulties, refer to our [Getting Started](/ui-kit/react/integration) guide. This guide will walk you through a step-by-step process of integrating our UI Kit into your React project. + +Ensure `CometChatUIKit.init(UIKitSettings)` has completed and the user is logged in via `CometChatUIKit.login("UID")`. See [React.js Integration](/ui-kit/react/react-js-integration). + -Once you've successfully integrated the UI Kit, the next step is to add the CometChat Calls SDK to your project. This is necessary to enable the calling features in the UI Kit. Here's how you do it: +## Integration -Add the SDK files to your project's dependencies or libraries: +Install the Calls SDK: -```java +```bash npm install @cometchat/calls-sdk-javascript ``` -After adding this dependency, the React UI Kit will automatically detect it and activate the calling features. Now, your application supports both audio and video calling. You will see [CallButtons](/ui-kit/react/call-buttons) component rendered in [MessageHeader](/ui-kit/react/message-header) Component. +The React UI Kit auto-detects the SDK and activates calling features. [CallButtons](/ui-kit/react/call-buttons) renders in [MessageHeader](/ui-kit/react/message-header). @@ -28,9 +38,7 @@ After adding this dependency, the React UI Kit will automatically detect it and ### Incoming Call -The [Incoming Call](/ui-kit/react/incoming-call) component of the CometChat UI Kit provides the functionality that lets users receive real-time audio and video calls in the app. - -When a call is made to a user, the Incoming Call component triggers and displays a call screen. This call screen typically displays the caller information and provides the user with options to either accept or reject the incoming call. +The [Incoming Call](/ui-kit/react/incoming-call) component displays a call screen when a call is received, showing caller info with accept/reject options. @@ -38,9 +46,7 @@ When a call is made to a user, the Incoming Call component triggers and displays ### Outgoing Call -The [Outgoing Call](/ui-kit/react/outgoing-call) component of the CometChat UI Kit is designed to manage the outgoing call process within your application. When a user initiates an audio or video call to another user or group, this component displays an outgoing call screen, showcasing information about the recipient and the call status. - -Importantly, the Outgoing Call component is smartly designed to transition automatically into the ongoing call screen once the receiver accepts the call. This ensures a smooth flow from initiating the call to engaging in a conversation, without any additional steps required from the user. +The [Outgoing Call](/ui-kit/react/outgoing-call) component displays an outgoing call screen with recipient info and call status. Transitions to the ongoing call screen when the receiver accepts. @@ -48,8 +54,25 @@ Importantly, the Outgoing Call component is smartly designed to transition autom ### Call Logs -[Call Logs](/ui-kit/react/call-logs) component provides you with the records call events such as who called who, the time of the call, and the duration of the call. This information can be fetched from the CometChat server and displayed in a structured format for users to view their past call activities. +The [Call Logs](/ui-kit/react/call-logs) component displays call history — caller, time, and duration. + +## Next Steps + + + + Audio and video call buttons + + + Incoming call notifications and UI + + + Call history and details + + + Core chat features + + diff --git a/ui-kit/react/call-logs.mdx b/ui-kit/react/call-logs.mdx index 35f786e34..49a9d3673 100644 --- a/ui-kit/react/call-logs.mdx +++ b/ui-kit/react/call-logs.mdx @@ -1,1151 +1,679 @@ --- title: "Call Logs" +description: "Scrollable list of call history entries with filtering, call-back actions, and custom views." --- + +```json +{ + "component": "CometChatCallLogs", + "package": "@cometchat/chat-uikit-react", + "import": "import { CometChatCallLogs } from \"@cometchat/chat-uikit-react\";", + "cssImport": "import \"@cometchat/chat-uikit-react/css-variables.css\";", + "description": "Scrollable list of call history entries with filtering, call-back actions, and custom views.", + "cssRootClass": ".cometchat-call-logs", + "primaryOutput": { + "prop": "onItemClick", + "type": "(call: any) => void" + }, + "props": { + "data": { + "callLogRequestBuilder": { + "type": "any (CallLogRequestBuilder)", + "default": "SDK default (30 per page)" + }, + "activeCall": { + "type": "any", + "default": "undefined" + }, + "callInitiatedDateTimeFormat": { + "type": "CalendarObject", + "default": "DD MMM, hh:mm A" + } + }, + "callbacks": { + "onItemClick": "(call: any) => void", + "onCallButtonClicked": "(call: any) => void", + "onError": "((error: CometChat.CometChatException) => void) | null" + }, + "visibility": { + "showScrollbar": { "type": "boolean", "default": false } + }, + "viewSlots": { + "itemView": "(call: any) => JSX.Element", + "leadingView": "(call: any) => JSX.Element", + "titleView": "(call: any) => JSX.Element", + "subtitleView": "(call: any) => JSX.Element", + "trailingView": "(call: any) => JSX.Element", + "loadingView": "JSX.Element", + "emptyView": "JSX.Element", + "errorView": "JSX.Element" + } + }, + "events": [ + { + "name": "CometChatMessageEvents.ccMessageSent", + "payload": "IMessages", + "description": "Call message sent" + } + ], + "types": { + "CalendarObject": { + "today": "string | undefined", + "yesterday": "string | undefined", + "lastWeek": "string | undefined", + "otherDays": "string | undefined" + } + } +} +``` + -## Overview - -`CometChatCallLogs` is a Component that shows the list of Call Log available . By default, names are shown for all listed users, along with their avatar if available. - - - - - -The `Call Logs` is comprised of the following components: - -| Components | Description | -| ----------------- | --------------------------------------------------------------------------------------------------------------------------- | -| CometChatList | A reusable container component having title, search box, customizable background and a list view. | -| CometChatListItem | A component that renders data obtained from a Group object on a Tile having a title, subtitle, leading and trailing view. | -| CometChatDate | This component used to show the date and time. You can also customize the appearance of this widget by modifying its logic. | - -## Usage +## Where It Fits -### Integration +`CometChatCallLogs` is a standalone list component that renders call history entries. Each entry shows the caller/callee, call type (audio/video), direction (incoming/outgoing/missed), and timestamp. The `onItemClick` callback emits the selected call log, and `onCallButtonClicked` fires when the call-back button is tapped. - - ```tsx import { CometChatCallLogs } from "@cometchat/chat-uikit-react"; -import React from "react"; - -const CallLogDemo = () => { - return ; -}; - -export default CallLogDemo; -``` +import "@cometchat/chat-uikit-react/css-variables.css"; - - - -```tsx -import { CallLogDemo } from "./CallLogDemo"; - -export default function App() { +function CallLogPanel() { return ( -
-
- -
+
+ { + console.log("Call log selected:", callLog); + }} + onCallButtonClicked={(callLog: any) => { + console.log("Call back:", callLog); + }} + />
); } ``` - - - - -### Actions - -[Actions](/ui-kit/react/components-overview#actions) dictate how a component functions. They are divided into two types: Predefined and User-defined. You can override either type, allowing you to tailor the behavior of the component to fit your specific needs. - -##### 1. onItemClick - -`onItemClick` is a callback function which triggers when a call log list item is clicked. It does not have a default behavior. However, you can override its behavior using the following code snippet. - - - -```ts -import { CometChatCallLogs } from "@cometchat/chat-uikit-react"; -import React from "react"; + + + -const CallLogDemo = () => { - const handleOnItemClick = (callLog: any) => { - console.log("custom on item click", callLog); - }; - return ; -}; +--- -export default CallLogDemo; -``` +## Minimal Render - - - -```js +```tsx import { CometChatCallLogs } from "@cometchat/chat-uikit-react"; -import React from "react"; +import "@cometchat/chat-uikit-react/css-variables.css"; -const CallLogDemo = () => { - const handleOnItemClick = (callLog) => { - console.log("custom on item click", callLog); - }; - return ; -}; +function CallLogsDemo() { + return ( +
+ +
+ ); +} -export default CallLogDemo; +export default CallLogsDemo; ``` -
- -
+Root CSS class: `.cometchat-call-logs` -##### 2. onCallButtonClicked - -`onCallButtonClicked` is a callback function which triggers when the call button in the trailing view is clicked. - - - -```ts -import { CometChatCallLogs } from "@cometchat/chat-uikit-react"; -import React from "react"; - -const CallLogDemo = () => { - const handleOnCallButtonClick = (callLog: any) => { - console.log("custom on info click", callLog); - }; - return ; -}; +--- -export default CallLogDemo; -``` +## Filtering Call Logs - +Pass a `CallLogRequestBuilder` from `@cometchat/calls-sdk-javascript` to `callLogRequestBuilder`. - -```js +```tsx +import { CallLogRequestBuilder } from "@cometchat/calls-sdk-javascript"; import { CometChatCallLogs } from "@cometchat/chat-uikit-react"; -import React from "react"; - -const CallLogDemo = () => { - const handleOnCallButtonClick = (callLog) => { - console.log("custom on info click", callLog); - }; - return ; -}; -export default CallLogDemo; +function FilteredCallLogs() { + return ( + + ); +} ``` - +### Filter Recipes - +| Recipe | Code | +| --- | --- | +| Limit to 5 per page | `new CallLogRequestBuilder().setAuthToken(token).setLimit(5)` | +| Cancelled calls only | `new CallLogRequestBuilder().setAuthToken(token).setCallStatus("cancelled")` | +| Video calls only | `new CallLogRequestBuilder().setAuthToken(token).setCallType("video")` | +| Calls with recordings | `new CallLogRequestBuilder().setAuthToken(token).setHasRecording(true)` | +| Calls for a specific user | `new CallLogRequestBuilder().setAuthToken(token).setUid("user_uid")` | +| Calls for a specific group | `new CallLogRequestBuilder().setAuthToken(token).setGuid("group_guid")` | -##### 3. onError +Refer to [CallLogRequestBuilder](/sdk/javascript/call-logs) for the full builder API. -This is a callback function which is triggered when the component encounters an error. +--- - - -```ts -import { CometChat } from "@cometchat/chat-sdk-javascript"; -import { CometChatCallLogs } from "@cometchat/chat-uikit-react"; -import React from "react"; +## Actions and Events -const CallLogDemo = () => { - const handleOnError = (error: CometChat.CometChatException) => { - console.log("your custom on error actions", error); - }; - return ; -}; +### Callback Props -export default CallLogDemo; -``` +#### onItemClick - +Fires when a call log entry is tapped. - -```js +```tsx import { CometChatCallLogs } from "@cometchat/chat-uikit-react"; -import React from "react"; -const CallLogDemo = () => { - const handleOnError = (error) => { - console.log("your custom on error actions", error); - }; - return ; -}; - -export default CallLogDemo; +function CallLogsWithClick() { + return ( + { + console.log("Selected call log:", callLog); + }} + /> + ); +} ``` - - - - -*** - -### Filters - -**Filters** allow you to customize the data displayed in a list within a `Component`. You can filter the list based on your specific criteria, allowing for a more customized. Filters can be applied using `RequestBuilders` of Chat SDK. +#### onCallButtonClicked -##### 1. CallLogRequestBuilder +Fires when the call-back button in the trailing view is tapped. -The [CallLogRequestBuilder](/sdk/javascript/call-logs) enables you to filter and customize the Call Log based on available parameters in [CallLogRequestBuilder](/sdk/javascript/call-logs). This feature allows you to create more specific and targeted queries when fetching the call logs. The following are the parameters available in [CallLogRequestBuilder](/sdk/javascript/call-logs) - -| Methods | Type | Description | -| -------------------- | ---------- | ------------------------------------------------------------ | -| **setLimit** | number | Specifies the number of call logs to fetch. | -| **setCallType** | String | Sets the type of calls to fetch (call or meet). | -| **setCallStatus** | callStatus | Sets the status of calls to fetch (initiated, ongoing, etc.) | -| **setHasRecording** | boolean | Sets whether to fetch calls that have recordings. | -| **setCallCategory** | string | Sets the category of calls to fetch (call or meet). | -| **setCallDirection** | string | Sets the direction of calls to fetch (incoming or outgoing) | -| **setUid** | string | Sets the UID of the user whose call logs to fetch. | -| **setGuid** | string | Sets the GUID of the user whose call logs to fetch. | -| **setAuthToken** | string | Sets the Auth token of the logged-in user. | - -**Example** - -In the example below, we're filtering Call Logs to show only canceled calls and setting the limit to five. - - - -```ts -import { CallLogRequestBuilder } from "@cometchat/calls-sdk-javascript"; +```tsx import { CometChatCallLogs } from "@cometchat/chat-uikit-react"; -import React from "react"; -const CallLogDemo = () => { +function CallLogsWithCallback() { return ( { + console.log("Call back:", callLog); + }} /> ); -}; - -export default CallLogDemo; +} ``` - +#### onError - -```js -import { CallLogRequestBuilder } from "@cometchat/calls-sdk-javascript"; +Fires on internal errors (network failure, auth issue, SDK exception). + +```tsx import { CometChatCallLogs } from "@cometchat/chat-uikit-react"; -import React from "react"; +import { CometChat } from "@cometchat/chat-sdk-javascript"; -const CallLogDemo = () => { +function CallLogsWithError() { return ( { + console.error("CometChatCallLogs error:", error); + }} /> ); -}; - -export default CallLogDemo; -``` - - - - - -*** - -### Events - -[Events](/ui-kit/react/components-overview#events) are emitted by a `Component`. By using event you can extend existing functionality. Being global events, they can be applied in Multiple Locations and are capable of being Added or Removed. - -The list of events emitted by the `Call Logs` component is as follows. - -| Event | Description | -| ----------------- | --------------------------------------------------------------------------------------------------------- | -| **ccMessageSent** | This event is triggered when the sent message is in transit and also when it is received by the receiver. | - -*** - - - -```tsx -const ccMessageSent = CometChatMessageEvents.ccMessageSent.subscribe(() => { - //Your Code -}); +} ``` - +### Global UI Events - +The component subscribes to `CometChatMessageEvents.ccMessageSent` to detect when a call message is sent and refresh the list. -*** +### SDK Events (Real-Time, Automatic) - - -```tsx -ccMessageSent?.unsubscribe(); -``` - - - - +The component listens to SDK call events internally for real-time updates. No manual attachment needed. -*** + +In React 18 StrictMode, `useEffect` runs twice on mount in development. The component handles listener cleanup internally. + -## Customization +--- -To fit your app's design requirements, you can customize the appearance of the Call Logs component. We provide exposed methods that allow you to modify the experience and behavior according to your specific needs. +## Custom View Slots -### Style +Each slot replaces a section of the default UI. Slots that accept a call log parameter receive the call log object for that row. -Using CSS you can customize the look and feel of the component in your app like the color, size, shape, and fonts. +| Slot | Signature | Replaces | +| --- | --- | --- | +| `itemView` | `(call: any) => JSX.Element` | Entire list item row | +| `leadingView` | `(call: any) => JSX.Element` | Avatar / left section | +| `titleView` | `(call: any) => JSX.Element` | Name / title text | +| `subtitleView` | `(call: any) => JSX.Element` | Call type, direction, timestamp | +| `trailingView` | `(call: any) => JSX.Element` | Call-back button area | +| `loadingView` | `JSX.Element` | Loading spinner | +| `emptyView` | `JSX.Element` | Empty state | +| `errorView` | `JSX.Element` | Error state | -**Example:** +### itemView - - - +Replace the entire call log list item. -```ts -import { CometChatCallLogs } from "@cometchat/chat-uikit-react"; -import React from "react"; - -const CallLogDemo = () => { - return ; -}; - -export default CallLogDemo; -``` - - - - -```js +```tsx import { CometChatCallLogs } from "@cometchat/chat-uikit-react"; -import React from "react"; -const CallLogDemo = () => { - return ; -}; +function CustomItemViewCallLogs() { + const getItemView = (callLog: any) => { + return ( +
+
+ {callLog?.getInitiator()?.getName()} +
+
+ {callLog?.getStatus()} +
+
+ ); + }; -export default CallLogDemo; + return ; +} ``` -
- - + ```css -.cometchat .cometchat-call-logs .cometchat-list__header-title { - background-color: #fce9ea; - color: #f76808; - border: 0px 1px 1px 0px solid #e5484d; - font-family: "Times New Roman"; -} - -.cometchat .cometchat-call-logs .cometchat-list-item__body-title { - overflow: hidden; - color: #141414; - text-overflow: ellipsis; - font-family: "Times New Roman"; - font-size: 16px; - font-style: normal; - font-weight: 400; - line-height: 19.2px; -} - -.cometchat .cometchat-call-logs .cometchat-list-item__body-subtitle { - overflow: hidden; - color: #727272; - text-overflow: ellipsis; - white-space: nowrap; - font-family: "Times New Roman"; - font-size: 14px; - font-style: normal; - font-weight: 400; - line-height: 16.8px; +.custom-call-log-item { + display: flex; + align-items: center; + justify-content: space-between; + padding: 8px 16px; + border-bottom: 1px solid var(--cometchat-border-color-light); } -.cometchat .cometchat-call-logs .cometchat-avatar { - border-radius: 8px; - background: #fbaa75; +.custom-call-log-item__name { + font: var(--cometchat-font-heading4-medium); + color: var(--cometchat-text-color-primary); } -.cometchat .cometchat-call-logs .cometchat-avatar__image { - border-radius: 8px; +.custom-call-log-item__status { + font: var(--cometchat-font-body-regular); + color: var(--cometchat-text-color-secondary); } ``` - -
-*** - -### Functionality - -These are a set of small functional customizations that allow you to fine-tune the overall experience of the component. With these, you can change text, set custom icons, and toggle the visibility of UI elements. +### subtitleView -Here is a code snippet demonstrating how you can customize the functionality of the `Call Logs` component. +Replace the subtitle text (call type, duration). -```ts -import { CometChatCallLogs } from "@cometchat/chat-uikit-react"; -import React from "react"; - -const CallLogDemo = () => { - return ; -}; - -export default CallLogDemo; -``` - - - - -```js +```tsx import { CometChatCallLogs } from "@cometchat/chat-uikit-react"; -import React from "react"; -const CallLogDemo = () => { - return ; -}; +function SubtitleCallLogs() { + const getSubtitleView = (callLog: any) => { + return ( +
+ {callLog?.getStatus()} • {callLog?.getType()} +
+ ); + }; -export default CallLogDemo; + return ; +} ``` -
- -
- -Below is a list of customizations along with corresponding code snippets - -| Property | Description | Code | -| ------------------ | --------------------------------------------------------------------------- | ----------------------------------------------------------------- | -| **Active Call** | Object representing the active call that is currently selected. | `activeCall={call}` | -| **Show Scrollbar** | Controls the visibility of the scrollbar in the list. | `showScrollbar={true}` | -| **Loading View** | A custom view to display when call logs are being loaded. | `loadingView={<>Custom Loading View}` | -| **Empty View** | A custom view to display when no call logs are available. | `emptyView={<>Custom Empty View}` | -| **Error View** | A custom view to display when an error occurs while fetching the call logs. | `errorView={<>Custom Error View}` | -| **Item View** | A function that renders a JSX element to display the item view. | `itemView={(call) => { return (<>Custom Item View)}}` | -| **Leading View** | A function that renders a JSX element to display the leading view. | `leadingView={(call) => { return (<>Custom Leading View)}}` | -| **Title View** | A function that renders a JSX element to display the title view. | `titleView={(call) => { return (<>Custom Title View)}}` | -| **Sub Title View** | A function that renders a JSX element to display the subtitle view. | `subtitleView={(call) => { return (<>Custom Sub Title View)}}` | -| **Trailing View** | A function that renders a JSX element to display the trailing view. | `trailingView={(call) => { return (<>Custom Trailing View)}}` | - -*** - -### Advanced - -For advanced-level customization, you can set custom views to the component. This lets you tailor each aspect of the component to fit your exact needs and application aesthetics. You can create and define your views, layouts, and UI elements and then incorporate those into the component. - -*** - -#### Call Initiated Date Time Format - -The `callInitiatedDateTimeFormat` property allows you to customize the **Call Initiated** timestamp displayed in the call logs. - -Default Date Time Format: - -```ruby -new CalendarObject({ - today: `DD MMM, hh:mm A`, // Example: "25 Jan, 10:30 AM" - yesterday: `DD MMM, hh:mm A`, // Example: "25 Jan, 10:30 AM" - otherDays: `DD MMM, hh:mm A`, // Example: "25 Jan, 10:30 AM" -}); -``` - -The following example demonstrates how to modify the **Call Initiated** timestamp format using a custom [`CalendarObject`](/ui-kit/react/localize#calendarobject). - - - -```ts -import { CometChatCallLogs, CalendarObject } from "@cometchat/chat-uikit-react"; - -// Define a custom date format pattern -function getDateFormat() { - const dateFormat = new CalendarObject({ - today: `hh:mm A`, // Example: "10:30 AM" - yesterday: `[yesterday]`, // Example: "yesterday" - otherDays: `DD/MM/YYYY`, // Example: "25/05/2025" - }); - return dateFormat; + +```css +.custom-call-log-subtitle { + font: var(--cometchat-font-body-regular); + color: var(--cometchat-text-color-secondary); } - -// Apply the custom format to the CometChatCallLogs component -; ``` - - - - -**Fallback Mechanism** - -* If you **do not** pass any property in the [**CalendarObject**](/ui-kit/react/localize#calendarobject), the component will first check the [**global configuration**](/ui-kit/react/localize#customisation). If the property is **also missing in the global configuration**, it will **fallback to the component's default formatting**. - - - -*** - -#### ItemView +### trailingView -With this property, you can assign a custom ListItem to the Call Logs Component. - -Shown below is the default chat interface. - - - - - -The customized chat interface is displayed below. - - - - - -Use the following code to achieve the customization shown above. +Replace the right section (call-back button area). -```ts -import { - CometChatCallLogs, - CometChatUIKitLoginListener, - isMissedCall, - isSentByMe, - verifyCallUser, -} from "@cometchat/chat-uikit-react"; +```tsx import { CometChatCallLogs } from "@cometchat/chat-uikit-react"; -const CallLogDemo = () => { - const getItemView = (call: any) => { - const missedCall = isMissedCall( - call, - CometChatUIKitLoginListener?.getLoggedInUser()! - ); - const isCallSentByMe = isSentByMe( - call, - CometChatUIKitLoginListener?.getLoggedInUser()! - ); - - let callStatus = missedCall - ? "Missed Call" - : isCallSentByMe - ? "Outgoing Call" - : "Incoming Call"; - - let callIcon = missedCall - ? missedIcon - : isCallSentByMe - ? outgoingIcon - : incomingIcon; - - function formatDate(timestamp: number) { - // Convert the timestamp from seconds to milliseconds - const date = new Date(timestamp * 1000); - - // Define options for formatting - const options: Object = { - day: "2-digit", - month: "short", - hour: "2-digit", - minute: "2-digit", - hour12: true, - }; - - // Format the date with the specified options - return date.toLocaleDateString("en-GB", options); - } - +function TrailingViewCallLogs() { + const getTrailingView = (callLog: any) => { return ( -
- +
+
); }; - return ; -}; - -export default CallLogDemo; -``` - - - - -```js -import { CometChatCallLogs, CometChatUIKitLoginListener, isMissedCall, isSentByMe, verifyCallUser } from "@cometchat/chat-uikit-react"; - -const CallLogDemo = () => { - const getItemView = (call) => { - const missedCall = isMissedCall(call, CometChatUIKitLoginListener?.getLoggedInUser()!); - const isCallSentByMe = isSentByMe(call, CometChatUIKitLoginListener?.getLoggedInUser()!); - - let callStatus = missedCall - ? "Missed Call" - : isCallSentByMe - ? "Outgoing Call" - : "Incoming Call"; - - let callIcon = missedCall - ? missedIcon - : isCallSentByMe - ? outgoingIcon - : incomingIcon; - - function formatDate(timestamp: number) { - // Convert the timestamp from seconds to milliseconds - const date = new Date(timestamp * 1000); - - // Define options for formatting - const options: Object = { - day: '2-digit', - month: 'short', - hour: '2-digit', - minute: '2-digit', - hour12: true, - }; - - // Format the date with the specified options - return date.toLocaleDateString('en-GB', options); - } - - return ( -
- -
- ) - } - return ; -}; - -export default CallLogDemo; + return ; +} ``` -
- - + ```css -.cometchat .cometchat-call-logs .cometchat-list-item__trailing-view { - width: auto; - overflow: hidden; - color: #727272; - text-overflow: ellipsis; - font: 400 14px/120% roboto; - font-style: normal; -} - -.cometchat .cometchat-call-logs .cometchat-avatar { - background-color: #edeafa; -} - -.cometchat .cometchat-call-logs .cometchat-avatar__image { - height: 24px; - width: 24px; -} - -.cometchat .cometchat-call-logs .cometchat-list-item__body-title { - overflow: hidden; - color: #141414; - text-overflow: ellipsis; - white-space: nowrap; - font: 500 16px/19.2px roboto; - font-style: normal; -} - -.cometchat .cometchat-call-logs .cometchat-list-item__body-subtitle { - overflow: hidden; - color: #727272; - text-overflow: ellipsis; - font: 400 14px/120% roboto; - font-style: normal; +.custom-call-log-trailing button { + background: var(--cometchat-primary-color); + color: var(--cometchat-static-white); + border: none; + border-radius: var(--cometchat-radius-2); + padding: 4px 12px; + cursor: pointer; } ``` - - -*** - -#### SubtitleView - -You can customize the subtitle view for each call logs item to meet your requirements. - -Shown below is the default chat interface. +### callInitiatedDateTimeFormat - - - - -The customized chat interface is displayed below. - - - - +Customize the call initiated timestamp format using a `CalendarObject`. -Use the following code to achieve the customization shown above. - - - -```ts +```tsx import { CometChatCallLogs, - CometChatUIKitLoginListener, - isMissedCall, - isSentByMe, + CalendarObject, } from "@cometchat/chat-uikit-react"; -import React from "react"; -const CallLogDemo = () => { - const getSubtitleView = (call: any): JSX.Element => { - const missedCall = isMissedCall( - call, - CometChatUIKitLoginListener?.getLoggedInUser()! - ); - const isCallSentByMe = isSentByMe( - call, - CometChatUIKitLoginListener?.getLoggedInUser()! - ); +function CustomDateCallLogs() { + const dateFormat = new CalendarObject({ + today: "hh:mm A", + yesterday: "[yesterday]", + otherDays: "DD MM YYYY", + }); - const iconClass = missedCall - ? "cometchat-call-logs__list-item-subtitle-icon-missed-call" - : isCallSentByMe - ? "cometchat-call-logs__list-item-subtitle-icon-outgoing-call" - : "cometchat-call-logs__list-item-subtitle-icon-incoming-call"; + return ; +} +``` - const callStatus = missedCall - ? "Missed Call" - : isCallSentByMe - ? "Outgoing Call" - : "Incoming Call"; + +If no property is passed in the [CalendarObject](/ui-kit/react/localize#calendarobject), the component checks the [global configuration](/ui-kit/react/localize#customisation) first. If also missing there, the component's default formatting applies. + - return ( - <> -
-
-
- {" "} - {callStatus} -
-
- - ); - }; +--- - return ; -}; +## Common Patterns -export default CallLogDemo; +### Custom empty state + +```tsx +import { CometChatCallLogs } from "@cometchat/chat-uikit-react"; + +function EmptyStateCallLogs() { + return ( + +

No call history

+
+ } + /> + ); +} ``` -
+### Filtered to video calls only - -```js -import { CometChatCallLogs,CometChatUIKitLoginListener,isMissedCall,isSentByMe } from "@cometchat/chat-uikit-react"; -import React from "react"; +```tsx +import { CallLogRequestBuilder } from "@cometchat/calls-sdk-javascript"; +import { CometChatCallLogs } from "@cometchat/chat-uikit-react"; -const CallLogDemo = () => { - const getSubtitleView = (call) => { +function VideoCallLogs({ authToken }: { authToken: string }) { + return ( + + ); +} +``` - const missedCall = isMissedCall(call, CometChatUIKitLoginListener?.getLoggedInUser()!); - const isCallSentByMe = isSentByMe(call, CometChatUIKitLoginListener?.getLoggedInUser()!); +--- - const iconClass = missedCall - ? "cometchat-call-logs__list-item-subtitle-icon-missed-call" - : isCallSentByMe - ? "cometchat-call-logs__list-item-subtitle-icon-outgoing-call" - : "cometchat-call-logs__list-item-subtitle-icon-incoming-call"; +## CSS Architecture + +The component uses CSS custom properties (design tokens) defined in `@cometchat/chat-uikit-react/css-variables.css`. The cascade: + +1. Global tokens are set on the `.cometchat` root wrapper. +2. Component CSS (`.cometchat-call-logs`) consumes these tokens via `var()` with fallback values. +3. Overrides target `.cometchat-call-logs` descendant selectors in a global stylesheet. + +### Key Selectors + +| Target | Selector | +| --- | --- | +| Root | `.cometchat-call-logs` | +| List item | `.cometchat-call-logs .cometchat-list-item` | +| Active item | `.cometchat-call-logs__list-item-active .cometchat-list-item` | +| Trailing view (video) | `.cometchat-call-logs__list-item-trailing-view-video` | +| Trailing view (audio) | `.cometchat-call-logs__list-item-trailing-view-audio` | +| Subtitle | `.cometchat-call-logs__list-item-subtitle` | +| Subtitle date | `.cometchat-call-logs__list-item-subtitle .cometchat-date` | +| Missed call icon | `.cometchat-call-logs__list-item-subtitle-icon-missed-call` | +| Outgoing call icon | `.cometchat-call-logs__list-item-subtitle-icon-outgoing-call` | +| Incoming call icon | `.cometchat-call-logs__list-item-subtitle-icon-incoming-call` | +| Empty state | `.cometchat-call-logs__empty-state-view` | +| Error state | `.cometchat-call-logs__error-state-view` | +| Shimmer loading | `.cometchat-call-logs__shimmer` | +| Outgoing call overlay | `.cometchat-call-logs__outgoing-call` | + +### Customization Matrix + +| What to change | Where | Property/API | Example | +| --- | --- | --- | --- | +| Override behavior on user interaction | Component props | `on` callbacks | `onItemClick={(c) => showDetails(c)}` | +| Filter which call logs appear | Component props | `callLogRequestBuilder` | `callLogRequestBuilder={new CallLogRequestBuilder().setLimit(5)}` | +| Replace a section of the list item | Component props | `View` render props | `subtitleView={(c) =>
{c.getStatus()}
}` | +| Change colors, fonts, spacing | Global CSS | Target `.cometchat-call-logs` class | `.cometchat-call-logs .cometchat-list-item { background: #f9f8fd; }` | - const callStatus = missedCall - ? "Missed Call" - : isCallSentByMe - ? "Outgoing Call" - : "Incoming Call"; +--- - return ( - <> -
-
-
- {callStatus} -
-
- - ) - } +## Accessibility - return ; -}; +The component renders a scrollable list of interactive items. Each call log row is keyboard-focusable and activates on Enter/Space. Call direction icons (incoming/outgoing/missed) use CSS mask images — add `aria-label` attributes via `itemView` if screen reader descriptions are needed. -export default CallLogDemo; -``` +--- - +--- - -```css -.cometchat-call-logs__list-item-subtitle-text { - overflow: hidden; - color: #727272; - text-overflow: ellipsis; - font: 400 14px/120% Roboto; - font-style: normal; -} -``` +## Props - +All props are optional. - +--- -*** +### activeCall -#### TrailingView +Highlights the currently active/selected call log entry. -You can customize the trailing view for each call logs item to meet your requirements. +| | | +| --- | --- | +| Type | `any` | +| Default | `undefined` | -Shown below is the default chat interface. +--- - - - +### callInitiatedDateTimeFormat -The customized chat interface is displayed below. +Format for displaying the call initiated timestamp. - - - +| | | +| --- | --- | +| Type | `CalendarObject` | +| Default | Component default (`DD MMM, hh:mm A`) | -Use the following code to achieve the customization shown above. +Falls back to [global calendar configuration](/ui-kit/react/localize#customisation) if not set. - - -```ts -import { CallLog } from "@cometchat/calls-sdk-javascript"; -import { CometChatCallLogs } from "@cometchat/chat-uikit-react"; -import React from "react"; - -const CallLogDemo = () => { - function formatDate(timestamp: number) { - // Convert the timestamp from seconds to milliseconds - const date = new Date(timestamp * 1000); - - // Define options for formatting - const options: Object = { - day: "2-digit", - month: "short", - hour: "2-digit", - minute: "2-digit", - hour12: true, - }; - - // Format the date with the specified options - return date.toLocaleDateString("en-GB", options); - } +--- - const getTrailingView = (call: any) => { - return ( -
- {formatDate(call?.getInitiatedAt())} -
- ); - }; +### callLogRequestBuilder - return ; -}; +Controls which call logs load and in what order. -export default CallLogDemo; -``` +| | | +| --- | --- | +| Type | `any` (CallLogRequestBuilder from `@cometchat/calls-sdk-javascript`) | +| Default | SDK default (30 per page) | -
+--- - -```js -import { CometChatCallLogs } from "@cometchat/chat-uikit-react"; -import React from "react"; - -const CallLogDemo = () => { - function formatDate(timestamp) { - // Convert the timestamp from seconds to milliseconds - const date = new Date(timestamp * 1000); - - // Define options for formatting - const options = { - day: "2-digit", - month: "short", - hour: "2-digit", - minute: "2-digit", - hour12: true, - }; - - // Format the date with the specified options - return date.toLocaleDateString("en-GB", options); - } +### emptyView - const getTrailingView = (call) => { - return ( -
- {formatDate(call?.getInitiatedAt())} -
- ); - }; +Custom component displayed when there are no call logs. - return ; -}; +| | | +| --- | --- | +| Type | `JSX.Element` | +| Default | Built-in empty state | -export default CallLogDemo; -``` +--- -
+### errorView - -```css -.cometchat .cometchat-call-logs .cometchat-list-item__trailing-view { - width: auto; - overflow: hidden; - color: #727272; - text-overflow: ellipsis; - font: 400 14px/120% roboto; - font-style: normal; -} -``` +Custom component displayed when an error occurs. - +| | | +| --- | --- | +| Type | `JSX.Element` | +| Default | Built-in error state | -
+--- -#### LeadingView +### itemView -You can customize the leading view for each call logs item to meet your requirements. +Custom renderer for the entire call log list item. -Shown below is the default chat interface. +| | | +| --- | --- | +| Type | `(call: any) => JSX.Element` | +| Default | Built-in list item | - - - +--- -The customized chat interface is displayed below. +### leadingView - - - +Custom renderer for the avatar / left section. -Use the following code to achieve the customization shown above. +| | | +| --- | --- | +| Type | `(call: any) => JSX.Element` | +| Default | Built-in avatar | - - -```ts -import { CallLog } from "@cometchat/calls-sdk-javascript"; -import { - CometChatUIKitLoginListener, - CometChatCallLogs, -} from "@cometchat/chat-uikit-react"; -import React from "react"; +--- -const CallLogDemo = () => { - const getLeadingView = (call: any) => { - const loggedInUser = CometChatUIKitLoginListener.getLoggedInUser(); - return ( -
- {call.status === "unanswered" || call.status === "cancelled" ? ( -
- ) : call.initiator?.uid === loggedInUser?.getUid() ? ( -
- ) : ( -
- )} -
- ); - }; +### loadingView - return ; -}; +Custom component displayed during the loading state. -export default CallLogDemo; -``` +| | | +| --- | --- | +| Type | `JSX.Element` | +| Default | Built-in shimmer | - +--- - -```js -import { - CometChatUIKitLoginListener, - CometChatCallLogs, -} from "@cometchat/chat-uikit-react"; -import React from "react"; +### onCallButtonClicked -const CallLogDemo = () => { - const getLeadingView = (call) => { - const loggedInUser = CometChatUIKitLoginListener.getLoggedInUser(); - return ( -
- {call.status === "unanswered" || call.status === "cancelled" ? ( -
- ) : call.initiator?.uid === loggedInUser?.getUid() ? ( -
- ) : ( -
- )} -
- ); - }; +Callback fired when the call-back button is clicked. - return ; -}; +| | | +| --- | --- | +| Type | `(call: any) => void` | +| Default | `undefined` | -export default CallLogDemo; -``` +--- - +### onError - -```css -.call-log-avatar { - display: flex; - width: 48px; - height: 48px; - padding: 8px; - justify-content: center; - align-items: center; - border-radius: 1000px; - background: #edeafa; -} +Callback fired when the component encounters an error. -.call-log-missed { - background-image: url(""); - background-size: contain; - height: 32px; - width: 32px; -} +| | | +| --- | --- | +| Type | `((error: CometChat.CometChatException) => void) \| null` | +| Default | `undefined` | -.call-log-incoming { - background-image: url(""); - background-size: contain; - height: 32px; - width: 32px; -} +--- -.call-log-outgoing { - background-image: url(""); - background-size: contain; - height: 32px; - width: 32px; -} -``` +### onItemClick - +Callback fired when a call log entry is clicked. - +| | | +| --- | --- | +| Type | `(call: any) => void` | +| Default | `undefined` | -#### TitleView +--- -You can customize the title view for each call logs item to meet your requirements. +### showScrollbar -Shown below is the default chat interface. +Shows the scrollbar in the call log list. - - - +| | | +| --- | --- | +| Type | `boolean` | +| Default | `false` | -The customized chat interface is displayed below. +--- - - - +### subtitleView -Use the following code to achieve the customization shown above. +Custom renderer for the subtitle text. - - -```ts -import { CallLog } from "@cometchat/calls-sdk-javascript"; -import { CometChatCallLogs } from "@cometchat/chat-uikit-react"; -import React from "react"; +| | | +| --- | --- | +| Type | `(call: any) => JSX.Element` | +| Default | Built-in subtitle | -const CallLogDemo = () => { - const getTitleView = (call: any) => { - return ( -
- {call.initiator?.name} - {call.status !== "unanswered" && call.status !== "cancelled" && ( - <>{" • 🕚️ " + Math.ceil(call.totalDurationInMinutes) + " mins"} - )} -
- ); - }; +--- - return ; -}; +### titleView -export default CallLogDemo; -``` +Custom renderer for the name / title text. -
+| | | +| --- | --- | +| Type | `(call: any) => JSX.Element` | +| Default | Built-in title | - -```js -import { CometChatCallLogs } from "@cometchat/chat-uikit-react"; -import React from "react"; +--- -const CallLogDemo = () => { - const getTitleView = (call) => { - return ( -
- {call.initiator?.name} - {call.status !== "unanswered" && call.status !== "cancelled" && ( - <>{" • 🕚️ " + Math.ceil(call.totalDurationInMinutes) + " mins"} - )} -
- ); - }; +### trailingView - return ; -}; +Custom renderer for the right section. -export default CallLogDemo; -``` +| | | +| --- | --- | +| Type | `(call: any) => JSX.Element` | +| Default | Built-in trailing view | -
+--- - -```css -.call-log-title { - overflow: hidden; - color: #141414; - text-overflow: ellipsis; - white-space: nowrap; - font: 500 16px Roboto; -} -``` +## Events - +| Event | Payload | Fires when | +| --- | --- | --- | +| `CometChatMessageEvents.ccMessageSent` | `IMessages` | Call message sent | -
+--- + +## CSS Selectors + +| Target | Selector | +| --- | --- | +| Root | `.cometchat-call-logs` | +| List item | `.cometchat-call-logs .cometchat-list-item` | +| Active item | `.cometchat-call-logs__list-item-active .cometchat-list-item` | +| Trailing view (video) | `.cometchat-call-logs__list-item-trailing-view-video` | +| Trailing view (audio) | `.cometchat-call-logs__list-item-trailing-view-audio` | +| Subtitle | `.cometchat-call-logs__list-item-subtitle` | +| Subtitle date | `.cometchat-call-logs__list-item-subtitle .cometchat-date` | +| Missed call icon | `.cometchat-call-logs__list-item-subtitle-icon-missed-call` | +| Outgoing call icon | `.cometchat-call-logs__list-item-subtitle-icon-outgoing-call` | +| Incoming call icon | `.cometchat-call-logs__list-item-subtitle-icon-incoming-call` | +| Empty state | `.cometchat-call-logs__empty-state-view` | +| Error state | `.cometchat-call-logs__error-state-view` | +| Shimmer loading | `.cometchat-call-logs__shimmer` | +| Outgoing call overlay | `.cometchat-call-logs__outgoing-call` | diff --git a/ui-kit/react/components-overview.mdx b/ui-kit/react/components-overview.mdx index dfc456255..38289fdad 100644 --- a/ui-kit/react/components-overview.mdx +++ b/ui-kit/react/components-overview.mdx @@ -1,29 +1,167 @@ --- title: "Overview" +description: "Browse all prebuilt UI components in the CometChat React UI Kit — conversations, messages, users, groups, calls, search, and AI." --- -CometChat's **UI Kit** is a set of pre-built UI components that allows you to easily craft an in-app chat with all the essential messaging features. + -## Actions +| Field | Value | +| --- | --- | +| Package | `@cometchat/chat-uikit-react` | +| Required setup | `CometChatUIKit.init()` + `CometChatUIKit.login()` before rendering any component | +| Callback actions | `on={(param) => {}}` | +| Data filtering | `RequestBuilder={new CometChat.RequestBuilder()}` | +| Toggle features | `hide={true}` or `show={true}` | +| Custom rendering | `View={() => JSX}` | +| CSS overrides | Target `.cometchat-` class in global CSS | +| Calling | Requires separate `@cometchat/calls-sdk-javascript` package | -Actions direct the operational behavior of a component. They are split into two categories: Predefined Actions and User-Defined Actions. + -### Predefined Actions +## Architecture -These are actions that are inherently programmed into a UI component. They are ingrained in the component itself by default, and they execute automatically in response to user interaction, without needing any additional user input. +The UI Kit is a set of independent components that compose into chat layouts. A typical two-panel layout uses four core components: -### User-Defined Actions +- CometChatConversations — sidebar listing recent conversations (users and groups) +- CometChatMessageHeader — toolbar showing avatar, name, online status, and typing indicator +- CometChatMessageList — scrollable message feed with reactions, receipts, and threads +- CometChatMessageComposer — rich text input with attachments, mentions, and voice notes -These are actions that must be explicitly specified by the user. They are not innately part of the component like predefined actions. Instead, they must be developed based on the unique needs of the user or the application. User-defined actions provide adaptability and allow for the creation of custom behaviors that align with the individual needs of the application. +Data flow: selecting a conversation in CometChatConversations yields a `CometChat.User` or `CometChat.Group` object. That object is passed as a prop (`user` or `group`) to CometChatMessageHeader, CometChatMessageList, and CometChatMessageComposer. The message components use the SDK internally — CometChatMessageComposer sends messages, CometChatMessageList receives them via real-time listeners. -To customize the behavior of a component, actions can be overridden by you. This provides you with control over how the component responds to specific events or interactions. +Components communicate through a publish/subscribe event bus (`CometChatMessageEvents`, `CometChatConversationEvents`, `CometChatGroupEvents`, etc.). A component emits events that other components or application code can subscribe to without direct references. See [Events](/ui-kit/react/events) for the full list. -All components expose actions to the user, which means that users can interact with these types of components through predefined or user-defined actions. +Each component accepts callback props (`on`), view slot props (`View`) for replacing UI sections, `RequestBuilder` props for data filtering, and CSS variable overrides on `.cometchat-` classes. -*** +--- + +## Component Catalog + +All components are imported from `@cometchat/chat-uikit-react`. + +### Conversations and Lists + +| Component | Purpose | Key Props | Page | +| --- | --- | --- | --- | +| CometChatConversations | Scrollable list of recent conversations | `conversationsRequestBuilder`, `onItemClick`, `onError` | [Conversations](/ui-kit/react/conversations) | +| CometChatUsers | Scrollable list of users | `usersRequestBuilder`, `onItemClick`, `onError` | [Users](/ui-kit/react/users) | +| CometChatGroups | Scrollable list of groups | `groupsRequestBuilder`, `onItemClick`, `onError` | [Groups](/ui-kit/react/groups) | +| CometChatGroupMembers | Scrollable list of group members | `group`, `groupMemberRequestBuilder`, `onItemClick` | [Group Members](/ui-kit/react/group-members) | + +### Messages + +| Component | Purpose | Key Props | Page | +| --- | --- | --- | --- | +| CometChatMessageHeader | Toolbar with avatar, name, status, typing indicator | `user`, `group`, `enableAutoSummaryGeneration` | [Message Header](/ui-kit/react/message-header) | +| CometChatMessageList | Scrollable message list with reactions, receipts, threads | `user`, `group`, `messagesRequestBuilder`, `goToMessageId` (string) | [Message List](/ui-kit/react/message-list) | +| CometChatMessageComposer | Rich text input with attachments, mentions, voice notes | `user`, `group`, `onSendButtonClick`, `placeholderText` | [Message Composer](/ui-kit/react/message-composer) | +| CometChatMessageTemplate | Pre-defined structure for custom message bubbles | `type`, `category`, `contentView`, `headerView`, `footerView` | [Message Template](/ui-kit/react/message-template) | +| CometChatThreadHeader | Parent message bubble and reply count for threaded view | `parentMessage`, `onClose`, `hideReceipts`, `textFormatters` | [Thread Header](/ui-kit/react/thread-header) | + +### Calling + +| Component | Purpose | Key Props | Page | +| --- | --- | --- | --- | +| CometChatCallButtons | Voice and video call initiation buttons | `user`, `group`, `onVoiceCallClick`, `onVideoCallClick` | [Call Buttons](/ui-kit/react/call-buttons) | +| CometChatIncomingCall | Incoming call notification with accept/decline | `call`, `onAccept(call)`, `onDecline(call)` | [Incoming Call](/ui-kit/react/incoming-call) | +| CometChatOutgoingCall | Outgoing call screen with cancel control | `call`, `onCloseClicked` | [Outgoing Call](/ui-kit/react/outgoing-call) | +| CometChatCallLogs | Scrollable list of call history | `callLogsRequestBuilder`, `onItemClick` | [Call Logs](/ui-kit/react/call-logs) | + +### Search and AI + +| Component | Purpose | Key Props | Page | +| --- | --- | --- | --- | +| CometChatSearch | Real-time search across conversations and messages | `onConversationClicked(conversation, searchKeyword?)`, `onMessageClicked(message, searchKeyword?)`, `uid`, `guid`, `textFormatters` | [Search](/ui-kit/react/search) | +| CometChatAIAssistantChat | AI agent chat with streaming, suggestions, history | `user`, `onSendButtonClick(message, previewMessageMode?)`, `aiAssistantTools` | [AI Assistant Chat](/ui-kit/react/ai-assistant-chat) | + +## Component API Pattern + +All components share a consistent API surface. + +### Actions + +Actions control component behavior. They split into two categories: + +**Predefined Actions** are built into the component and execute automatically on user interaction (e.g., clicking send dispatches the message). No configuration needed. + +**User-Defined Actions** are callback props that fire on specific events. Override them to customize behavior: -## Events +```tsx + openThreadPanel(message)} + onError={(error) => logError(error)} +/> +``` + +### Events + +Events enable decoupled communication between components. A component emits events that other parts of the application can subscribe to without direct references. + +```tsx +import { CometChatMessageEvents } from "@cometchat/chat-uikit-react"; + +const sub = CometChatMessageEvents.ccMessageSent.subscribe((message) => { + // react to sent message +}); + +// cleanup +sub?.unsubscribe(); +``` + +Each component page documents its emitted events in the Events section. + +### Filters + +List-based components accept `RequestBuilder` props to control which data loads: + +```tsx + +``` + +### Custom View Slots + +Components expose named view slots to replace sections of the default UI: + +```tsx +} + subtitleView={} + leadingView={} +/> +``` + +### CSS Overrides + +Every component has a root CSS class (`.cometchat-`) for style customization: + +```css +.cometchat-message-list .cometchat-text-bubble__body-text { + font-family: "SF Pro"; +} +``` + +--- -Events allow for a decoupled, flexible architecture where different parts of the application can interact without having to directly reference each other. This makes it easier to create complex, interactive experiences, as well as to extend and customize the functionality provided by the CometChat UI Kit. +## Next Steps -All Components have the ability to emit events. These events are dispatched in response to certain changes or user interactions within the component. By emitting events, these components allow other parts of the application to react to changes or interactions, thus enabling dynamic and interactive behavior within the application. + + + Chat features included out of the box + + + Customize colors, fonts, and styles + + + Add-on features like polls, stickers, and translation + + + Task-oriented tutorials for common patterns + + diff --git a/ui-kit/react/conversations.mdx b/ui-kit/react/conversations.mdx index a148e2bb6..06fadd3c7 100644 --- a/ui-kit/react/conversations.mdx +++ b/ui-kit/react/conversations.mdx @@ -1,379 +1,504 @@ --- title: "Conversations" +description: "Scrollable list of recent one-on-one and group conversations for the logged-in user." --- + +```json +{ + "component": "CometChatConversations", + "package": "@cometchat/chat-uikit-react", + "import": "import { CometChatConversations } from \"@cometchat/chat-uikit-react\";", + "cssImport": "import \"@cometchat/chat-uikit-react/css-variables.css\";", + "description": "Scrollable list of recent one-on-one and group conversations for the logged-in user.", + "cssRootClass": ".cometchat-conversations", + "primaryOutput": { + "prop": "onItemClick", + "type": "(conversation: CometChat.Conversation) => void" + }, + "props": { + "data": { + "conversationsRequestBuilder": { + "type": "CometChat.ConversationsRequestBuilder", + "default": "SDK default (30 per page)", + "note": "Pass the builder, not the result of .build()" + }, + "activeConversation": { + "type": "CometChat.Conversation", + "default": "undefined" + }, + "lastMessageDateTimeFormat": { + "type": "CalendarObject", + "default": "Component default (hh:mm A today, [yesterday], DD/MM/YYYY other days)", + "note": "Falls back to global CometChatLocalize.calendarObject if not set" + } + }, + "callbacks": { + "onItemClick": "(conversation: CometChat.Conversation) => void", + "onSelect": "(conversation: CometChat.Conversation, selected: boolean) => void", + "onError": "((error: CometChat.CometChatException) => void) | null", + "onSearchBarClicked": "() => void" + }, + "visibility": { + "hideReceipts": { "type": "boolean", "default": false }, + "hideError": { "type": "boolean", "default": false }, + "hideDeleteConversation": { "type": "boolean", "default": false }, + "hideUserStatus": { "type": "boolean", "default": false }, + "hideGroupType": { "type": "boolean", "default": false }, + "showSearchBar": { "type": "boolean", "default": false }, + "showScrollbar": { "type": "boolean", "default": false } + }, + "sound": { + "disableSoundForMessages": { "type": "boolean", "default": false }, + "customSoundForMessages": { "type": "string", "default": "built-in" } + }, + "selection": { + "selectionMode": { + "type": "SelectionMode", + "values": ["SelectionMode.single (0)", "SelectionMode.multiple (1)", "SelectionMode.none (2)"], + "default": "SelectionMode.none" + } + }, + "viewSlots": { + "itemView": "(conversation: CometChat.Conversation) => JSX.Element", + "leadingView": "(conversation: CometChat.Conversation) => JSX.Element", + "titleView": "(conversation: CometChat.Conversation) => JSX.Element", + "subtitleView": "(conversation: CometChat.Conversation) => JSX.Element", + "trailingView": "(conversation: CometChat.Conversation) => JSX.Element", + "headerView": "JSX.Element", + "searchView": "JSX.Element", + "loadingView": "JSX.Element", + "emptyView": "JSX.Element", + "errorView": "JSX.Element", + "options": "((conversation: CometChat.Conversation) => CometChatOption[]) | null" + }, + "formatting": { + "textFormatters": { + "type": "CometChatTextFormatter[]", + "default": "default formatters from data source" + } + } + }, + "events": [ + { + "name": "CometChatConversationEvents.ccConversationDeleted", + "payload": "CometChat.Conversation", + "description": "Conversation deleted from list" + }, + { + "name": "CometChatConversationEvents.ccUpdateConversation", + "payload": "CometChat.Conversation", + "description": "Conversation updated" + }, + { + "name": "CometChatConversationEvents.ccMarkConversationAsRead", + "payload": "CometChat.Conversation", + "description": "Conversation marked as read" + } + ], + "sdkListeners": [ + "onTextMessageReceived", + "onMediaMessageReceived", + "onCustomMessageReceived", + "onTypingStarted", + "onTypingEnded", + "onMessagesDelivered", + "onMessagesRead", + "onMessagesDeliveredToAll", + "onMessagesReadByAll", + "onUserOnline", + "onUserOffline", + "onGroupMemberJoined", + "onGroupMemberLeft", + "onGroupMemberKicked", + "onGroupMemberBanned", + "onMemberAddedToGroup" + ], + "compositionExample": { + "description": "Sidebar conversations wired to message view", + "components": [ + "CometChatConversations", + "CometChatMessageHeader", + "CometChatMessageList", + "CometChatMessageComposer" + ], + "flow": "onItemClick emits CometChat.Conversation -> extract User/Group via getConversationWith() -> pass to MessageHeader, MessageList, MessageComposer" + }, + "types": { + "CalendarObject": { + "today": "string | undefined", + "yesterday": "string | undefined", + "lastWeek": "string | undefined", + "otherDays": "string | undefined", + "relativeTime": { + "minute": "string | undefined", + "minutes": "string | undefined", + "hour": "string | undefined", + "hours": "string | undefined" + } + }, + "CometChatOption": { + "id": "string | undefined", + "title": "string | undefined", + "iconURL": "string | undefined", + "onClick": "(() => void) | undefined" + }, + "SelectionMode": { + "single": 0, + "multiple": 1, + "none": 2 + } + } +} +``` + -## Overview - -The Conversations is a Component, that shows all conversations related to the currently logged-in user. - -This component lists the most recent or latest conversations or contacts with whom you have exchanged messages. It provides a convenient way to quickly access and resume conversations with the people you have been in contact with recently. - - - - - -## Usage +## Where It Fits -### Integration +`CometChatConversations` is a sidebar list component. It renders recent conversations and emits the selected `CometChat.Conversation` via `onItemClick`. Wire it to `CometChatMessageHeader`, `CometChatMessageList`, and `CometChatMessageComposer` to build a standard two-panel chat layout. - - ```tsx +import { useState } from "react"; import { CometChatConversations, - TitleAlignment, + CometChatMessageHeader, + CometChatMessageList, + CometChatMessageComposer, } from "@cometchat/chat-uikit-react"; +import { CometChat } from "@cometchat/chat-sdk-javascript"; +import "@cometchat/chat-uikit-react/css-variables.css"; + +function ChatApp() { + const [selectedUser, setSelectedUser] = useState(); + const [selectedGroup, setSelectedGroup] = useState(); + + const handleItemClick = (conversation: CometChat.Conversation) => { + const entity = conversation.getConversationWith(); + if (entity instanceof CometChat.User) { + setSelectedUser(entity); + setSelectedGroup(undefined); + } else if (entity instanceof CometChat.Group) { + setSelectedGroup(entity); + setSelectedUser(undefined); + } + }; -function ConversationsDemo() { return ( -
-
- +
+
+
+ {selectedUser || selectedGroup ? ( +
+ + + +
+ ) : ( +
+ Select a conversation +
+ )}
); } - -export default ConversationsDemo; ``` - +[Open in CodeSandbox](https://link.cometchat.com/react-conversation-list-message) + + + + + +--- + +## Minimal Render - ```tsx -import { ConversationsDemo } from "./ConversationsDemo"; +import { CometChatConversations } from "@cometchat/chat-uikit-react"; +import "@cometchat/chat-uikit-react/css-variables.css"; -export default function App() { +function ConversationsDemo() { return ( -
- +
+
); } -``` - +export default ConversationsDemo; +``` - + + + -### Actions +Root CSS class: `.cometchat-conversations` -[Actions](/ui-kit/react/components-overview#actions) dictate how a component functions. They are divided into two types: Predefined and User-defined. You can override either type, allowing you to tailor the behavior of the component to fit your specific needs. +--- -#### 1. OnItemClick +## Filtering Conversations -`OnItemClick` is triggered when you click on a ListItem of the Conversations component. The `OnItemClick` action doesn't have a predefined behavior. You can override this action using the following code snippet. +Pass a `CometChat.ConversationsRequestBuilder` to `conversationsRequestBuilder`. Pass the builder instance — not the result of `.build()`. - - ```tsx import { CometChatConversations } from "@cometchat/chat-uikit-react"; +import { CometChat } from "@cometchat/chat-sdk-javascript"; -const getOnItemClick = (conversation: CometChat.Conversation) => { - console.log("ItemClick:", conversation); - // Your custom action here -}; - -; +function FilteredConversations() { + return ( + + ); +} ``` - - - - -*** - -#### 2. OnSelect +### Filter Recipes -The `OnSelect` event is triggered upon the completion of a selection in `SelectionMode`. It does not have a default behavior. However, you can override its behavior using the following code snippet. +| Recipe | Code | +| --- | --- | +| Only user conversations | `new CometChat.ConversationsRequestBuilder().setConversationType("user")` | +| Only group conversations | `new CometChat.ConversationsRequestBuilder().setConversationType("group")` | +| Limit to 10 per page | `new CometChat.ConversationsRequestBuilder().setLimit(10)` | +| With specific tags | `new CometChat.ConversationsRequestBuilder().setTags(["vip"])` | +| Filter by user tags | `new CometChat.ConversationsRequestBuilder().withUserAndGroupTags(true).setUserTags(["premium"])` | +| Filter by group tags | `new CometChat.ConversationsRequestBuilder().withUserAndGroupTags(true).setGroupTags(["support"])` | - - -```tsx -import { - CometChatConversations, - SelectionMode, -} from "@cometchat/chat-uikit-react"; +Default page size is 30. The component uses infinite scroll — the next page loads as the user scrolls to the bottom. -const getOnSelect = ( - conversation: CometChat.Conversation, - selected: boolean -) => { - console.log("Selected, ", conversation.getConversationId(), selected); - // Your custom action on select -}; - -; -``` +Refer to [ConversationRequestBuilder](/sdk/javascript/retrieve-conversations) for the full builder API. - +--- - +## Actions and Events -*** +### Callback Props -#### 3. OnError +#### onItemClick -This action doesn't change the behavior of the component but rather listens for any errors that occur in the Conversations component. +Fires when a conversation row is tapped. Primary navigation hook — set the active conversation and render the message view. - - ```tsx import { CometChatConversations } from "@cometchat/chat-uikit-react"; +import { CometChat } from "@cometchat/chat-sdk-javascript"; -const handleOnError = (error: CometChat.CometChatException) => { - // Your exception handling code -}; +function ConversationsWithClick() { + const handleItemClick = (conversation: CometChat.Conversation) => { + console.log("Selected:", conversation.getConversationId()); + }; -; + return ; +} ``` - - - - -*** +#### onSelect -#### 4. onSearchBarClicked +Fires when a conversation is checked/unchecked in multi-select mode. Requires `selectionMode` to be set. -The `onSearchBarClicked` event is triggered when the user clicks the search bar. It does not have a default behavior. However, you can override its behavior using the following code snippet. - - - ```tsx -import { CometChatConversations } from "@cometchat/chat-uikit-react"; - -const handleSearchClick = () => { - console.log("Search bar clicked"); -}; - -; -``` - - - - +import { useState } from "react"; +import { + CometChatConversations, + SelectionMode, +} from "@cometchat/chat-uikit-react"; +import { CometChat } from "@cometchat/chat-sdk-javascript"; -*** +function BatchSelectDemo() { + const [selected, setSelected] = useState>(new Set()); -### Filters + const handleSelect = (conversation: CometChat.Conversation, isSelected: boolean) => { + setSelected((prev) => { + const next = new Set(prev); + const id = conversation.getConversationId(); + isSelected ? next.add(id) : next.delete(id); + return next; + }); + }; -You can set `ConversationsRequestBuilder` in the Conversations Component to filter the conversation list. You can modify the builder as per your specific requirements with multiple options available to know more refer to [ConversationRequestBuilder](/sdk/javascript/retrieve-conversations). + return ( + + ); +} +``` -You can set filters using the following parameters. +#### onError -1. **Conversation Type:** Filters on type of Conversation, `User` or `Groups` -2. **Limit:** Number of conversations fetched in a single request. -3. **WithTags:** Filter on fetching conversations containing tags -4. **Tags:** Filters on specific `Tag` -5. **UserTags:** Filters on specific User `Tag` -6. **GroupTags:** Filters on specific Group `Tag` +Fires on internal errors (network failure, auth issue, SDK exception). - - ```tsx import { CometChatConversations } from "@cometchat/chat-uikit-react"; import { CometChat } from "@cometchat/chat-sdk-javascript"; -; -``` - - - - - -*** - -### Events - -[Events](/ui-kit/react/components-overview#events) are emitted by a `Component`. By using event you can extend existing functionality. Being global events, they can be applied in Multiple Locations and are capable of being Added or Removed. - - - -```tsxtsx -const ccConversationDeleted = - CometChatConversationEvents.ccConversationDeleted.subscribe( - (conversation: CometChat.Conversation) => { - // Your code here - } +function ConversationsWithErrorHandler() { + return ( + { + console.error("CometChatConversations error:", error); + }} + /> ); +} ``` - +#### onSearchBarClicked - +Fires when the search bar is clicked. Requires `showSearchBar={true}`. -*** +```tsx +import { CometChatConversations } from "@cometchat/chat-uikit-react"; - - -```tsxtsx -ccConversationDeleted?.unsubscribe(); +function ConversationsWithSearch() { + return ( + { + console.log("Search bar clicked"); + }} + /> + ); +} ``` - - - - -## Customization +### Global UI Events -To fit your app's design requirements, you can customize the appearance of the conversation component. We provide exposed methods that allow you to modify the experience and behavior according to your specific needs. +`CometChatConversationEvents` emits events subscribable from anywhere in the application. Subscribe in a `useEffect` and unsubscribe on cleanup. -### Style +| Event | Fires when | Payload | +| --- | --- | --- | +| `ccConversationDeleted` | A conversation is deleted from the list | `CometChat.Conversation` | +| `ccUpdateConversation` | A conversation is updated (last message change, metadata update) | `CometChat.Conversation` | +| `ccMarkConversationAsRead` | A conversation is marked as read | `CometChat.Conversation` | -Using CSS you can customize the look and feel of the component in your app like the color, size, shape, and fonts. - - - - +When to use: sync external UI with conversation state changes. For example, update an unread count badge in a tab bar when `ccMarkConversationAsRead` fires, or remove a conversation from a custom sidebar when `ccConversationDeleted` fires. - - ```tsx - -``` - - - - -```css -.cometchat-conversations .cometchat-list-item__body-title, -.cometchat-conversations .cometchat-list__header-title, -.cometchat-conversations .cometchat-avatar__text, -.cometchat-conversations .cometchat-badge, -.cometchat-conversations .cometchat-conversations__subtitle-text { - font-family: "SF Pro"; -} - -.cometchat-conversations .cometchat-list__header-title { - background: #fef8f8; - border-bottom: 2px solid #f4b6b8; -} - -.cometchat-conversations .cometchat-avatar { - background: #f0999b; -} - -.cometchat-conversations .cometchat-status-indicator { - min-width: 10px; - height: 10px; -} +import { useEffect } from "react"; +import { CometChatConversationEvents } from "@cometchat/chat-uikit-react"; +import { CometChat } from "@cometchat/chat-sdk-javascript"; -.cometchat-conversations .cometchat-badge { - background: #e5484d; -} +function useConversationEvents() { + useEffect(() => { + const deletedSub = CometChatConversationEvents.ccConversationDeleted.subscribe( + (conversation: CometChat.Conversation) => { + console.log("Deleted:", conversation.getConversationId()); + } + ); + const updatedSub = CometChatConversationEvents.ccUpdateConversation.subscribe( + (conversation: CometChat.Conversation) => { + console.log("Updated:", conversation.getConversationId()); + } + ); + const readSub = CometChatConversationEvents.ccMarkConversationAsRead.subscribe( + (conversation: CometChat.Conversation) => { + console.log("Marked as read:", conversation.getConversationId()); + } + ); -.cometchat-conversations .cometchat-receipts-read { - background: #e96b6f; + return () => { + deletedSub?.unsubscribe(); + updatedSub?.unsubscribe(); + readSub?.unsubscribe(); + }; + }, []); } ``` - - - - -### Functionality +### SDK Events (Real-Time, Automatic) -These are a set of small functional customizations that allow you to fine-tune the overall experience of the component. With these, you can change text, set custom icons, and toggle the visibility of UI elements. +The component listens to these SDK events internally. No manual attachment needed unless additional side effects are required. - - -```tsx -
-
- -
-
-``` +| SDK Listener | Internal behavior | +| --- | --- | +| `onTextMessageReceived` / `onMediaMessageReceived` / `onCustomMessageReceived` | Moves conversation to top, updates last message preview and unread count | +| `onTypingStarted` / `onTypingEnded` | Shows/hides typing indicator in the subtitle | +| `onMessagesDelivered` / `onMessagesRead` / `onMessagesDeliveredToAll` / `onMessagesReadByAll` | Updates receipt ticks (unless `hideReceipts={true}`) | +| `onUserOnline` / `onUserOffline` | Updates online/offline status dot (unless `hideUserStatus={true}`) | +| `onGroupMemberJoined` / `onGroupMemberLeft` / `onGroupMemberKicked` / `onGroupMemberBanned` / `onMemberAddedToGroup` | Updates group conversation metadata | -
+Automatic: new messages, typing indicators, receipts, user presence, group membership changes. -
+Manual: deleting a conversation via the SDK directly (not through the component's context menu) requires emitting `CometChatConversationEvents.ccConversationDeleted` for the UI to update. -Below is a list of customizations along with corresponding code snippets + +In React 18 StrictMode, `useEffect` runs twice on mount in development. The component handles listener cleanup internally, but any additional listeners added alongside the component need cleanup in the `useEffect` return function to avoid duplicate event handling. + -| Property | Description | Code | -| ------------------------------ | --------------------------------------------------------------------------------------------------------------------------- | ------------------------------------------------ | -| **Hide Receipts** | Disables the display of message read receipts. If set to `true`, the receipt status of the sent message won't be displayed. | `hideReceipts={false}` | -| **Hide Error** | Hides the default and the custom error view passed in the `errorView` prop. | `hideError={true}` | -| **Hide Delete Conversation** | Hides the delete conversation option in the default context menu. | `hideDeleteConversation={false}` | -| **Hide User Status** | Hides the user's online/offline status indicator. | `hideUserStatus={true}` | -| **Hide Group Type** | Hides the group type icon. | `hideGroupType={false}` | -| **Show Search Bar** | Shows the search bar. | `showSearchBar={true}` | -| **Active Conversation** | Specifies the conversation to highlight in the list. | `activeConversation={activeConversation}` | -| **Selection Mode** | Determines the selection mode for the component. | `selectionMode={SelectionMode.multiple}` | -| **Disable Sound For Messages** | Used to Disable sound for incoming messages. | `disableSoundForMessages={false}` | -| **Custom Sound For Messages** | Custom audio sound for incoming messages. | `customSoundForMessages="Your custom sound url"` | -| **Search View** | A custom search view which replaces the default search bar. | `searchView={<>Custom Search View}` | -| **Loading View** | A custom component to display during the loading state. | `loadingView={<>Custom Loading View}` | -| **Empty View** | A custom component to display when there are no conversations available. | `emptyView={<>Custom Empty View}` | -| **Error View** | A custom component to display when an error occurs. | `errorView={<>Custom Error View}` | +--- -### Advanced +## Custom View Slots -For advanced-level customization, you can set custom views to the component. This lets you tailor each aspect of the component to fit your exact needs and application aesthetics. You can create and define your views, layouts, and UI elements and then incorporate those into the component. +Each slot replaces a section of the default UI. Slots that accept a conversation parameter receive the `CometChat.Conversation` object for that row. -*** +| Slot | Signature | Replaces | +| --- | --- | --- | +| `itemView` | `(conversation: CometChat.Conversation) => JSX.Element` | Entire list item row | +| `leadingView` | `(conversation: CometChat.Conversation) => JSX.Element` | Avatar / left section | +| `titleView` | `(conversation: CometChat.Conversation) => JSX.Element` | Name / title text | +| `subtitleView` | `(conversation: CometChat.Conversation) => JSX.Element` | Last message preview | +| `trailingView` | `(conversation: CometChat.Conversation) => JSX.Element` | Timestamp / badge / right section | +| `headerView` | `JSX.Element` | Entire header bar | +| `searchView` | `JSX.Element` | Search bar | +| `loadingView` | `JSX.Element` | Loading spinner | +| `emptyView` | `JSX.Element` | Empty state | +| `errorView` | `JSX.Element` | Error state | +| `options` | `(conversation: CometChat.Conversation) => CometChatOption[]` | Context menu / hover actions | -#### ItemView +### itemView -With this function, you can assign a custom ListItem to the Conversations Component. +Replace the entire list item row. -Shown below is the default chat interface. +Default: -The customized chat interface is displayed below. +Customized: -Use the following code to achieve the customization shown above. - -```ts +```tsx import { CometChat } from "@cometchat/chat-sdk-javascript"; import { CometChatListItem, CometChatConversations, + CometChatDate, } from "@cometchat/chat-uikit-react"; -const getItemView = (conversation: CometChat.Conversation) => { - const title = conversation.getConversationWith().getName(); - const timestamp = conversation?.getLastMessage()?.getSentAt(); +function CustomItemViewConversations() { + const getItemView = (conversation: CometChat.Conversation) => { + const title = conversation.getConversationWith().getName(); + const timestamp = conversation?.getLastMessage()?.getSentAt(); - return ( - } - onListItemClicked={() => { - // Logic here - }} - /> - ); -}; + return ( + } + onListItemClicked={() => { + // handle click + }} + /> + ); + }; -; + return ; +} ``` - - - + ```css .cometchat-conversations .cometchat-avatar { border-radius: 8px; @@ -385,164 +510,139 @@ const getItemView = (conversation: CometChat.Conversation) => { gap: 4px; } ``` - - -*** +### leadingView -#### LeadingView - -The customized chat interface is displayed below. +Replace the avatar / left section. Typing-aware avatar example. -Use the following code to achieve the customization shown above. - - - -```ts -import React from "react"; +```tsx +import { useEffect, useRef, useState } from "react"; import { CometChat } from "@cometchat/chat-sdk-javascript"; import { CometChatConversations, CometChatAvatar, + CometChatUIKitLoginListener, } from "@cometchat/chat-uikit-react"; -import { useEffect, useRef, useState } from "react"; -const [isTyping, setIsTyping] = useState(false); -const typingObjRef = useRef(null); - -useEffect(() => { - //adding typing listeners - const messageListenerId: string = "typing_demo_" + new Date().getTime(); - CometChat.addMessageListener( - messageListenerId, - new CometChat.MessageListener({ - onTypingStarted: (typingIndicator: CometChat.TypingIndicator) => { - typingObjRef.current = typingIndicator; - setIsTyping(true); - }, - onTypingEnded: (typingIndicator: CometChat.TypingIndicator) => { - if ( - typingObjRef.current && - typingObjRef.current.getSender().getUid() == - typingIndicator.getSender().getUid() - ) { - typingObjRef.current = null; - setIsTyping(false); - } - }, - }) - ); - return () => { - CometChat.removeMessageListener(messageListenerId); - }; -}, [setIsTyping]); - -// Custom leading view component -const CustomLeadingView = (conversation: CometChat.Conversation) => { - const conversationObj = conversation.getConversationWith(); - const isUser = conversationObj instanceof CometChat.User; - const isGroup = conversationObj instanceof CometChat.Group; - - // Check if the current user is typing - const isMyTyping = isUser - ? (conversationObj as CometChat.User).getUid() === - typingObjRef.current?.getSender().getUid() && - loggedInUser?.getUid() === typingObjRef.current?.getReceiverId() - : isGroup && - (conversationObj as CometChat.Group).getGuid() === - typingObjRef.current?.getReceiverId(); - - // Determine avatar and name - const avatar = isUser - ? (conversationObj as CometChat.User).getAvatar() - : (conversationObj as CometChat.Group).getIcon(); - const name = isTyping && isMyTyping ? undefined : conversationObj.getName(); - const image = isTyping && isMyTyping ? "TYPING_ICON_HERE" : avatar; - return ( -
- -
- ); -}; -; -``` +function TypingAwareConversations() { + const [isTyping, setIsTyping] = useState(false); + const typingObjRef = useRef(null); + const loggedInUser = CometChatUIKitLoginListener.getLoggedInUser(); + + useEffect(() => { + const listenerId = "typing_demo_" + Date.now(); + CometChat.addMessageListener( + listenerId, + new CometChat.MessageListener({ + onTypingStarted: (typingIndicator: CometChat.TypingIndicator) => { + typingObjRef.current = typingIndicator; + setIsTyping(true); + }, + onTypingEnded: (typingIndicator: CometChat.TypingIndicator) => { + if ( + typingObjRef.current && + typingObjRef.current.getSender().getUid() === + typingIndicator.getSender().getUid() + ) { + typingObjRef.current = null; + setIsTyping(false); + } + }, + }) + ); + return () => { + CometChat.removeMessageListener(listenerId); + }; + }, []); -
+ const getLeadingView = (conversation: CometChat.Conversation) => { + const entity = conversation.getConversationWith(); + const isUser = entity instanceof CometChat.User; + const isGroup = entity instanceof CometChat.Group; -
+ const isMyTyping = isUser + ? (entity as CometChat.User).getUid() === + typingObjRef.current?.getSender().getUid() && + loggedInUser?.getUid() === typingObjRef.current?.getReceiverId() + : isGroup && + (entity as CometChat.Group).getGuid() === + typingObjRef.current?.getReceiverId(); + + const avatar = isUser + ? (entity as CometChat.User).getAvatar() + : (entity as CometChat.Group).getIcon(); + + return ( +
+ +
+ ); + }; -*** + return ; +} +``` -#### TrailingView +### trailingView -The customized chat interface is displayed below. +Replace the timestamp / badge / right section. Relative time badge example. -Use the following code to achieve the customization shown above. - -```ts -import React from "react"; +```tsx import { CometChat } from "@cometchat/chat-sdk-javascript"; import { CometChatConversations } from "@cometchat/chat-uikit-react"; -// Custom trailing view component -const CustomTrailingButtonView = (conv: CometChat.Conversation) => { - if (!conv.getLastMessage()) { - return <>; - } - const timestamp = conv.getLastMessage()?.getSentAt() * 1000; - const now = new Date(); - const time = new Date(timestamp); - - // Calculate time difference - const diffInMs = now.getTime() - time.getTime(); - const diffInMinutes = Math.floor(diffInMs / (1000 * 60)); - const diffInHours = Math.floor(diffInMs / (1000 * 60 * 60)); - - // Determine the labels - let backgroundColorClass = "conversations__trailing-view-min"; // Default (less than 1 hour) - let topLabel = `${diffInMinutes}`; // Default minutes - let bottomLabel = `${diffInMinutes === 1 ? "Min ago" : "Mins ago"}`; // Default "Mins ago" - - if (diffInHours >= 1 && diffInHours <= 10) { - // 1-10 hours - backgroundColorClass = "conversations__trailing-view-hour"; - topLabel = `${diffInHours}`; - bottomLabel = `${diffInHours === 1 ? "Hour ago" : "Hours ago"}`; - } else if (diffInHours > 10) { - // More than 10 hours - backgroundColorClass = "conversations__trailing-view-date"; - topLabel = time.toLocaleDateString("en-US", { day: "numeric" }); - bottomLabel = time.toLocaleDateString("en-US", { - month: "short", - year: "numeric", - }); - } - return ( -
- {topLabel} - {bottomLabel} -
- ); -}; +function RelativeTimeConversations() { + const getTrailingView = (conv: CometChat.Conversation) => { + if (!conv.getLastMessage()) return <>; + + const timestamp = conv.getLastMessage()?.getSentAt() * 1000; + const now = Date.now(); + const diffInMinutes = Math.floor((now - timestamp) / (1000 * 60)); + const diffInHours = Math.floor((now - timestamp) / (1000 * 60 * 60)); + + let className = "conversations__trailing-view-min"; + let topLabel = `${diffInMinutes}`; + let bottomLabel = diffInMinutes === 1 ? "Min ago" : "Mins ago"; + + if (diffInHours >= 1 && diffInHours <= 10) { + className = "conversations__trailing-view-hour"; + topLabel = `${diffInHours}`; + bottomLabel = diffInHours === 1 ? "Hour ago" : "Hours ago"; + } else if (diffInHours > 10) { + className = "conversations__trailing-view-date"; + const time = new Date(timestamp); + topLabel = time.toLocaleDateString("en-US", { day: "numeric" }); + bottomLabel = time.toLocaleDateString("en-US", { month: "short", year: "numeric" }); + } -; -``` + return ( +
+ {topLabel} + {bottomLabel} +
+ ); + }; + return ; +} +```
- - + ```css .conversations__trailing-view { display: flex; @@ -553,282 +653,191 @@ const CustomTrailingButtonView = (conv: CometChat.Conversation) => { height: 40px; border-radius: 8px; box-shadow: 0 2px 4px rgba(0, 0, 0, 0.1); - font-family: Arial, sans-serif; -} - -.conversations__trailing-view-min { - background-color: #e0d4f7; -} - -.conversations__trailing-view-hour { - background-color: #fff3cd; } -.conversations__trailing-view-date { - background-color: #f8d7da; -} +.conversations__trailing-view-min { background-color: #e0d4f7; } +.conversations__trailing-view-hour { background-color: #fff3cd; } +.conversations__trailing-view-date { background-color: #f8d7da; } .conversations__trailing-view-time { - font-size: 20px; - font-weight: bold; + font: 600 18px Roboto; color: #4a3f99; margin-bottom: 4px; - font: 600 18px Roboto; } .conversations__trailing-view-status { font: 600 8px Roboto; color: #6a5b99; } + .cometchat-conversations .cometchat-list-item__trailing-view { height: 50px; } ``` - -
-*** +### titleView -#### TextFormatters +Replace the name / title text. Inline user status example. -Assigns the list of text formatters. If the provided list is not null, it sets the list. Otherwise, it assigns the default text formatters retrieved from the data source. To configure the existing Mentions look and feel check out [CometChatMentionsFormatter](/ui-kit/react/mentions-formatter-guide) + + + - -```ts -import { CometChatTextFormatter } from "@cometchat/chat-uikit-react"; -import DialogHelper from "./Dialog"; + +```tsx import { CometChat } from "@cometchat/chat-sdk-javascript"; +import { CometChatConversations } from "@cometchat/chat-uikit-react"; -class ShortcutFormatter extends CometChatTextFormatter { - private shortcuts: { [key: string]: string } = {}; - private dialogIsOpen: boolean = false; - private dialogHelper = new DialogHelper(); - private currentShortcut: string | null = null; // Track the currently open shortcut - - constructor() { - super(); - this.setTrackingCharacter("!"); - CometChat.callExtension("message-shortcuts", "GET", "v1/fetch", undefined) - .then((data: any) => { - if (data && data.shortcuts) { - this.shortcuts = data.shortcuts; - } - }) - .catch((error) => console.log("error fetching shortcuts", error)); - } - - onKeyDown(event: KeyboardEvent) { - const caretPosition = - this.currentCaretPosition instanceof Selection - ? this.currentCaretPosition.anchorOffset - : 0; - const textBeforeCaret = this.getTextBeforeCaret(caretPosition); - - const match = textBeforeCaret.match(/!([a-zA-Z]+)$/); - if (match) { - const shortcut = match[0]; - const replacement = this.shortcuts[shortcut]; - if (replacement) { - // Close the currently open dialog, if any - if (this.dialogIsOpen && this.currentShortcut !== shortcut) { - this.closeDialog(); - } - this.openDialog(replacement, shortcut); - } - } - } +function StatusTitleConversations() { + const getTitleView = (conversation: CometChat.Conversation) => { + const user = + conversation.getConversationType() === "user" + ? (conversation.getConversationWith() as CometChat.User) + : undefined; - getCaretPosition() { - if (!this.currentCaretPosition?.rangeCount) return { x: 0, y: 0 }; - const range = this.currentCaretPosition?.getRangeAt(0); - const rect = range.getBoundingClientRect(); - return { - x: rect.left, - y: rect.top, - }; - } - - openDialog(buttonText: string, shortcut: string) { - this.dialogHelper.createDialog( - () => this.handleButtonClick(buttonText), - buttonText + return ( +
+ + {user + ? conversation.getConversationWith().getName() + " · " + : conversation.getConversationWith().getName()} + + {user && ( + + {user.getStatusMessage()} + + )} +
); - this.dialogIsOpen = true; - this.currentShortcut = shortcut; - } - - closeDialog() { - this.dialogHelper.closeDialog(); // Use DialogHelper to close the dialog - this.dialogIsOpen = false; - this.currentShortcut = null; - } - - handleButtonClick = (buttonText: string) => { - if (this.currentCaretPosition && this.currentRange) { - // Inserting the replacement text corresponding to the shortcut - const shortcut = Object.keys(this.shortcuts).find( - (key) => this.shortcuts[key] === buttonText - ); - if (shortcut) { - const replacement = this.shortcuts[shortcut]; - this.addAtCaretPosition( - replacement, - this.currentCaretPosition, - this.currentRange - ); - } - } - if (this.dialogIsOpen) { - this.closeDialog(); - } }; - getFormattedText(text: string): string { - return text; - } + return ; +} +``` +
+ +```css +.cometchat-conversations .conversations__title-view { + display: flex; + gap: 4px; + width: 100%; +} - private getTextBeforeCaret(caretPosition: number): string { - if ( - this.currentRange && - this.currentRange.startContainer && - typeof this.currentRange.startContainer.textContent === "string" - ) { - const textContent = this.currentRange.startContainer.textContent; - if (textContent.length >= caretPosition) { - return textContent.substring(0, caretPosition); - } - } - return ""; - } +.conversations__title-view-name { + color: #141414; + font: 500 16px/19.2px Roboto; } -export default ShortcutFormatter; +.conversations__title-view-status { + color: #6852d6; + font: 400 16px/19.2px Roboto; +} ``` - +
- -```tsx -import React from "react"; -import ReactDOM from "react-dom"; +### subtitleView -interface DialogProps { - onClick: () => void; - buttonText: string; -} +Replace the last message preview text. -const Dialog: React.FC = ({ onClick, buttonText }) => { - console.log("buttonText", buttonText); +Default: - return ( -
- -
- ); -}; + + + + +Customized: + + + + -export default class DialogHelper { - private dialogContainer: HTMLDivElement | null = null; + + +```tsx +import { CometChat } from "@cometchat/chat-sdk-javascript"; +import { CometChatConversations } from "@cometchat/chat-uikit-react"; - createDialog(onClick: () => void, buttonText: string) { - this.dialogContainer = document.createElement("div"); - document.body.appendChild(this.dialogContainer); +function formatTimestamp(timestamp: number): string { + return new Date(timestamp * 1000).toLocaleString(); +} - ReactDOM.render( - , - this.dialogContainer +function SubtitleConversations() { + const getSubtitleView = (conversation: CometChat.Conversation) => { + if (conversation.getConversationType() === "user") { + return ( + <> + Last active:{" "} + {formatTimestamp( + (conversation.getConversationWith() as CometChat.User).getLastActiveAt() + )} + + ); + } + return ( + <> + Created:{" "} + {formatTimestamp( + (conversation.getConversationWith() as CometChat.Group).getCreatedAt() + )} + ); - } + }; - closeDialog() { - if (this.dialogContainer) { - ReactDOM.unmountComponentAtNode(this.dialogContainer); - this.dialogContainer.remove(); - this.dialogContainer = null; - } - } + return ; } ``` - - - -```tsx -import ShortcutFormatter from "./ShortCutFormatter"; - -; + +```css +.cometchat-conversations .cometchat-list-item__body-subtitle { + overflow: hidden; + color: var(--cometchat-text-color-secondary, #727272); + text-overflow: ellipsis; + white-space: nowrap; + font: var(--cometchat-font-body-regular); +} ``` - - -#### Header View - -You can set the Custom Header view to add more options to the Conversations component. +### headerView -The customized chat interface is displayed below. +Replace the entire header bar. -Use the following code to achieve the customization shown above. - -```ts +```tsx import { CometChatButton, CometChatConversations, + getLocalizedString, } from "@cometchat/chat-uikit-react"; -const getHeaderView = () => { +function CustomHeaderConversations() { return ( -
-
{localize("CHATS")}
- { - // logic here - }} - iconURL={ICON_URL} - /> -
+ +
+ {getLocalizedString("CHATS")} +
+ { /* handle click */ }} /> +
+ } + /> ); -}; - -; +} ``` -
- - + ```css .conversations__header { display: flex; @@ -837,332 +846,732 @@ const getHeaderView = () => { align-items: center; justify-content: space-between; gap: 12px; - flex: 1 0 0; - align-self: stretch; border-radius: 10px; border: 1px solid #e8e8e8; background: #edeafa; } + .conversations__header__title { overflow: hidden; color: #141414; text-overflow: ellipsis; font: 700 24px Roboto; } + .conversations__header .cometchat-button .cometchat-button__icon { background: #141414; } + .conversations__header .cometchat-button { width: 24px; border: none; background: transparent; border-radius: 0; - display: block; } ``` + + + +### options + +Replace the context menu / hover actions on each conversation item. + +Default: + + + + + +Customized: + + + + + + + +```tsx +import { CometChat } from "@cometchat/chat-sdk-javascript"; +import { + CometChatOption, + CometChatConversations, +} from "@cometchat/chat-uikit-react"; +function CustomOptionsConversations() { + const getOptions = (conversation: CometChat.Conversation) => [ + new CometChatOption({ + title: "Delete", + id: "delete", + onClick: () => { /* delete logic */ }, + }), + new CometChatOption({ + title: "Mute Notification", + id: "mute", + onClick: () => { /* mute logic */ }, + }), + new CometChatOption({ + title: "Mark as Unread", + id: "unread", + onClick: () => { /* mark unread logic */ }, + }), + new CometChatOption({ + title: "Block", + id: "block", + onClick: () => { /* block logic */ }, + }), + ]; + + return ; +} +``` + +```css +.cometchat-conversations .cometchat-menu-list__main-menu-item-icon-delete { + background: red; +} +.cometchat-conversations .cometchat-menu-list__sub-menu { + background: transparent; + box-shadow: none; +} +``` + -*** +```ts +// CometChatOption interface +interface CometChatOption { + id?: string; // Unique identifier + title?: string; // Display text + iconURL?: string; // Icon asset URL + onClick?: () => void; // Click handler +} +``` -#### Last Message Date Time Format +### textFormatters -The `lastMessageDateTimeFormat` property allows you to customize the **Last Message** timestamp is displayed in the conversations. +Custom text formatters for the conversation subtitle. Array of `CometChatTextFormatter` instances. If not provided, default formatters from the data source are used. -Default Date Time Format: +```tsx +import { CometChatConversations } from "@cometchat/chat-uikit-react"; +import ShortcutFormatter from "./ShortCutFormatter"; -```ruby -new CalendarObject({ - today: `hh:mm A`, // Example: "10:30 AM" - yesterday: `[yesterday]`, // Example: "yesterday" - otherDays: `DD/MM/YYYY`, // Example: "25/05/2025" -}); +function FormattedConversations() { + return ( + + ); +} ``` -The following example demonstrates how to modify the **Last Message** timestamp format using a custom [`CalendarObject`](/ui-kit/react/localize#calendarobject). +See [CometChatMentionsFormatter](/ui-kit/react/mentions-formatter-guide) for mention formatting. + +### lastMessageDateTimeFormat + +Customize the last message timestamp format using a `CalendarObject`. - - ```ts +// CalendarObject interface (from source) +class CalendarObject { + today?: string; + yesterday?: string; + lastWeek?: string; + otherDays?: string; + relativeTime?: { + minute?: string; + minutes?: string; + hour?: string; + hours?: string; + }; +} +``` + +```tsx import { CometChatConversations, CalendarObject, } from "@cometchat/chat-uikit-react"; -// Define a custom date format pattern -function getDateFormat() { +function CustomDateConversations() { const dateFormat = new CalendarObject({ - today: `DD MMM, hh:mm A`, // Example: "25 Jan, 10:30 AM" - yesterday: `DD MMM, hh:mm A`, // Example: "25 Jan, 10:30 AM" - otherDays: `DD MMM, hh:mm A`, // Example: "25 Jan, 10:30 AM" + today: "DD MMM, hh:mm A", + yesterday: "DD MMM, hh:mm A", + otherDays: "DD MMM, hh:mm A", }); - return dateFormat; -} -// Apply the custom format to the CometChatConversations component -; + return ; +} ``` - - - - +If no property is passed in the [CalendarObject](/ui-kit/react/localize#calendarobject), the component checks the [global configuration](/ui-kit/react/localize#customisation) first. If also missing there, the component's default formatting applies. + -**Fallback Mechanism** +--- -* If you **do not** pass any property in the [**CalendarObject**](/ui-kit/react/localize#calendarobject), the component will first check the [**global configuration**](/ui-kit/react/localize#customisation). If the property is **also missing in the global configuration**, it will **fallback to the component's default formatting**. +## Common Patterns - +### Custom empty state with CTA -*** +```tsx +import { CometChatConversations } from "@cometchat/chat-uikit-react"; -#### TitleView +function EmptyStateConversations() { + return ( + +

No conversations yet

+ +
+ } + /> + ); +} +``` -The customized chat interface is displayed below. +### Hide all chrome — minimal list - - - +```tsx +import { CometChatConversations } from "@cometchat/chat-uikit-react"; -Use the following code to achieve the customization shown above. +function MinimalConversations() { + return ( + + ); +} +``` - - -```ts -import React from "react"; -import { CometChat } from "@cometchat/chat-sdk-javascript"; +### Conversations with search + +```tsx import { CometChatConversations } from "@cometchat/chat-uikit-react"; -// Custom title view component -const customTitleView = (conversation: CometChat.Conversation) => { - let user = - conversation.getConversationType() == "user" - ? (conversation.getConversationWith() as CometChat.User) - : undefined; +function SearchableConversations() { return ( -
- - {user - ? conversation.getConversationWith().getName() + " • " - : conversation.getConversationWith().getName()} - - {user ? ( - - {user.getStatusMessage()} - - ) : null} -
+ ); -}; +} +``` + +--- + +## CSS Architecture + +The component uses CSS custom properties (design tokens) defined in `@cometchat/chat-uikit-react/css-variables.css`. The cascade: -; +1. Global tokens (e.g., `--cometchat-primary-color`, `--cometchat-background-color-01`) are set on the `.cometchat` root wrapper. +2. Component CSS (`.cometchat-conversations`) consumes these tokens via `var()` with fallback values. +3. Overrides target `.cometchat-conversations` descendant selectors in a global stylesheet. + +To scope overrides to a single instance when multiple `CometChatConversations` exist on the same page, wrap the component in a container and scope selectors: + +```css +.sidebar-left .cometchat-conversations .cometchat-badge { + background: #e5484d; +} ``` -
+Overrides survive component updates because the component never sets inline styles on these elements — all styling flows through CSS classes and custom properties. + +### Key Selectors + +| Target | Selector | +| --- | --- | +| Root | `.cometchat-conversations` | +| Header title | `.cometchat-conversations .cometchat-list__header-title` | +| List item | `.cometchat-conversations .cometchat-list-item` | +| Body title | `.cometchat-conversations .cometchat-list-item__body-title` | +| Avatar | `.cometchat-conversations .cometchat-avatar` | +| Avatar text | `.cometchat-conversations .cometchat-avatar__text` | +| Unread badge | `.cometchat-conversations .cometchat-badge` | +| Subtitle text | `.cometchat-conversations .cometchat-conversations__subtitle-text` | +| Status indicator | `.cometchat-conversations .cometchat-status-indicator` | +| Read receipts | `.cometchat-conversations .cometchat-receipts-read` | +| Active item | `.cometchat-conversations__list-item-active .cometchat-list-item` | +| Typing indicator | `.cometchat-conversations__subtitle-typing` | +| Trailing view | `.cometchat-conversations__trailing-view` | + +### Example: Brand-themed conversations + + + + - ```css -.cometchat-conversations .conversations__title-view { - display: flex; - gap: 4px; - width: 100%; +.cometchat-conversations .cometchat-list-item__body-title, +.cometchat-conversations .cometchat-list__header-title, +.cometchat-conversations .cometchat-avatar__text, +.cometchat-conversations .cometchat-badge, +.cometchat-conversations .cometchat-conversations__subtitle-text { + font-family: "SF Pro"; } -.cometchat-conversations - .conversations__title-view - .conversations__title-view-name { - color: #141414; - font: 500 16px/19.2px Roboto; - text-align: left; +.cometchat-conversations .cometchat-list__header-title { + background: #fef8f8; + border-bottom: 2px solid #f4b6b8; } -.cometchat-conversations - .conversations__title-view - .conversations__title-view-status { - color: #6852d6; - font: 400 16px/19.2px Roboto; - text-align: left; + +.cometchat-conversations .cometchat-avatar { + background: #f0999b; +} + +.cometchat-conversations .cometchat-status-indicator { + min-width: 10px; + height: 10px; +} + +.cometchat-conversations .cometchat-badge { + background: #e5484d; +} + +.cometchat-conversations .cometchat-receipts-read { + background: #e96b6f; } ``` - +### Customization Matrix -
+| What to change | Where | Property/API | Example | +| --- | --- | --- | --- | +| Override behavior on user interaction | Component props | `on` callbacks | `onItemClick={(c) => setActive(c)}` | +| Filter which conversations appear | Component props | `conversationsRequestBuilder` | `conversationsRequestBuilder={new CometChat.ConversationsRequestBuilder().setLimit(10)}` | +| Toggle visibility of UI elements | Component props | `hide` boolean props | `hideReceipts={true}` | +| Replace a section of the list item | Component props | `View` render props | `itemView={(conversation) =>
...
}` | +| Change colors, fonts, spacing | Global CSS | Target `.cometchat-conversations` class | `.cometchat-conversations .cometchat-badge { background: #e5484d; }` | -*** +--- -#### SubtitleView +## Accessibility -You can customize the subtitle view for each conversation item to meet your requirements. +The component renders a scrollable list of interactive items. Each conversation row is keyboard-focusable and activates on Enter/Space. The context menu (options) is accessible via keyboard. The unread badge count is exposed as text content. Avatar images include the conversation name as alt text. -Shown below is the default chat interface. +For screen readers, the conversation list is rendered as a semantic list. Status indicators (online/offline, group type icons) use CSS mask images — add `aria-label` attributes via `itemView` if screen reader descriptions are needed for these visual indicators. - - - +--- -The customized chat interface is displayed below. +--- - - - +## Props -Use the following code to achieve the customization shown above. +All props are optional. Sorted alphabetically. - - -```ts -import { CometChat } from "@cometchat/chat-sdk-javascript"; -import { CometChatConversations } from "@cometchat/chat-uikit-react"; +### activeConversation -const subtitleView = (conversation: CometChat.Conversation) => { - if (conversation.getConversationType() === "user") { - return ( - <> - Last Message at:{" "} - {getFormattedTimestamp( - ( - conversation.getConversationWith() as CometChat.User - ).getLastActiveAt() - )} - - ); - } else { - return ( - <> - Created at:{" "} - {getFormattedTimestamp( - (conversation.getConversationWith() as CometChat.Group).getCreatedAt() - )} - - ); - } -}; +Highlights the specified conversation in the list. -function getFormattedTimestamp(timestamp: number): string { - const date = new Date(timestamp * 1000); - return date.toLocaleString(); -} +| | | +| --- | --- | +| Type | `CometChat.Conversation` | +| Default | `undefined` | -; -``` +Must be a reference-equal object from the SDK; a manually constructed object will not match. - +--- - -```css -.cometchat-conversations .cometchat-list-item__body-subtitle { - overflow: hidden; - color: var(--cometchat-text-color-secondary, #727272); - text-overflow: ellipsis; - white-space: nowrap; - font: var(--cometchat-font-body-regular); - font-family: "SF Pro"; - font-style: normal; +### conversationsRequestBuilder + +Controls which conversations load and in what order. + +| | | +| --- | --- | +| Type | `CometChat.ConversationsRequestBuilder` | +| Default | SDK default (30 per page) | + +Pass the builder instance, not the result of `.build()`. + +--- + +### customSoundForMessages + +URL to a custom audio file for incoming message notifications. + +| | | +| --- | --- | +| Type | `string` | +| Default | Built-in sound | + +Must be a valid audio URL accessible from the browser. + +--- + +### disableSoundForMessages + +Disables the notification sound for incoming messages. + +| | | +| --- | --- | +| Type | `boolean` | +| Default | `false` | + +--- + +### emptyView + +Custom component displayed when there are no conversations. + +| | | +| --- | --- | +| Type | `JSX.Element` | +| Default | Built-in empty state | + +--- + +### errorView + +Custom component displayed when an error occurs. + +| | | +| --- | --- | +| Type | `JSX.Element` | +| Default | Built-in error state | + +Hidden when `hideError={true}`. + +--- + +### headerView + +Custom component rendered as the entire header bar. + +| | | +| --- | --- | +| Type | `JSX.Element` | +| Default | Built-in header with title | + +--- + +### hideDeleteConversation + +Hides the delete option in the context menu. + +| | | +| --- | --- | +| Type | `boolean` | +| Default | `false` | + +--- + +### hideError + +Hides the default and custom error views. + +| | | +| --- | --- | +| Type | `boolean` | +| Default | `false` | + +Also suppresses `errorView` if set. + +--- + +### hideGroupType + +Hides the group type icon (public/private/password). + +| | | +| --- | --- | +| Type | `boolean` | +| Default | `false` | + +--- + +### hideReceipts + +Hides message read/delivery receipt indicators. + +| | | +| --- | --- | +| Type | `boolean` | +| Default | `false` | + +--- + +### hideUserStatus + +Hides the online/offline status indicator. + +| | | +| --- | --- | +| Type | `boolean` | +| Default | `false` | + +--- + +### itemView + +Custom renderer for the entire list item row. + +| | | +| --- | --- | +| Type | `(conversation: CometChat.Conversation) => JSX.Element` | +| Default | Built-in list item | + +--- + +### lastMessageDateTimeFormat + +Format for displaying the timestamp of the last message. + +| | | +| --- | --- | +| Type | `CalendarObject` | +| Default | Component default (`hh:mm A` today, `[yesterday]`, `DD/MM/YYYY` other days) | + +```ts +class CalendarObject { + today?: string; + yesterday?: string; + lastWeek?: string; + otherDays?: string; + relativeTime?: { + minute?: string; + minutes?: string; + hour?: string; + hours?: string; + }; } ``` - +Falls back to [global calendar configuration](/ui-kit/react/localize#customisation) if not set. - +--- -*** +### leadingView -#### Options +Custom renderer for the avatar / left section. -A function that returns a list of actions available when hovering over a conversation item. +| | | +| --- | --- | +| Type | `(conversation: CometChat.Conversation) => JSX.Element` | +| Default | Built-in avatar | -Shown below is the default chat interface. +--- - - - +### loadingView -The customized chat interface is displayed below. +Custom component displayed during the loading state. - - - +| | | +| --- | --- | +| Type | `JSX.Element` | +| Default | Built-in shimmer | -Use the following code to achieve the customization shown above. +--- - - -```ts -import { - CometChatOption, - CometChatConversations, -} from "@cometchat/chat-uikit-react"; +### onError -const getOptions = (conversation: CometChat.Conversation) => { - return [ - new CometChatOption({ - title: "Delete", - iconURL: deleteIcon, - id: "delete", - onClick: () => { - // Logic here - }, - }), - new CometChatOption({ - title: "Mute Notification", - id: "mute", - onClick: () => { - // Logic here - }, - }), - new CometChatOption({ - title: "Mark as Unread", - id: "unread", - onClick: () => { - // Logic here - }, - }), - new CometChatOption({ - title: "Block", - id: "block", - onClick: () => { - // Logic here - }, - }), - ]; -}; +Callback fired when the component encounters an error. -; -``` +| | | +| --- | --- | +| Type | `((error: CometChat.CometChatException) => void) \| null` | +| Default | `undefined` | - +--- - -```css -.cometchat-conversations .cometchat-menu-list__main-menu-item-icon-delete { - background: red; -} +### onItemClick -.cometchat-conversations .cometchat-menu-list__sub-menu { - background: transparent; - box-shadow: none; +Callback fired when a conversation row is clicked. + +| | | +| --- | --- | +| Type | `(conversation: CometChat.Conversation) => void` | +| Default | `undefined` | + +--- + +### onSearchBarClicked + +Callback fired when the search bar is clicked. Requires `showSearchBar={true}`. + +| | | +| --- | --- | +| Type | `() => void` | +| Default | `undefined` | + +--- + +### onSelect + +Callback fired when a conversation is selected/deselected. Requires `selectionMode` to be set. + +| | | +| --- | --- | +| Type | `(conversation: CometChat.Conversation, selected: boolean) => void` | +| Default | `undefined` | + +--- + +### options + +Custom context menu / hover actions for each conversation item. + +| | | +| --- | --- | +| Type | `((conversation: CometChat.Conversation) => CometChatOption[]) \| null` | +| Default | Built-in delete option | + +```ts +class CometChatOption { + id?: string; + title?: string; + iconURL?: string; + onClick?: () => void; } +``` + +--- -.cometchat-conversations .cometchat-menu-list__sub-menu-icon { - -webkit-mask: url(./assets/down-arrow.svg) center center no-repeat; - -webkit-mask-size: contain; +### searchView + +Custom search bar component in the header. + +| | | +| --- | --- | +| Type | `JSX.Element` | +| Default | Built-in search bar | + +--- + +### selectionMode + +Enables single or multi-select checkboxes on list items. + +| | | +| --- | --- | +| Type | `SelectionMode` | +| Default | `SelectionMode.none` | + +```ts +enum SelectionMode { + single, // 0 + multiple, // 1 + none, // 2 } ``` - +Must pair with `onSelect` to capture selections. - +--- + +### showScrollbar + +Shows the scrollbar in the conversation list. + +| | | +| --- | --- | +| Type | `boolean` | +| Default | `false` | -##### Structure of CometChatOption +--- + +### showSearchBar + +Shows a search bar at the top of the list. + +| | | +| --- | --- | +| Type | `boolean` | +| Default | `false` | + +--- + +### subtitleView + +Custom renderer for the last message preview text. -| Name | Description | -| ----------- | ----------------------------------------------------- | -| **id** | Unique identifier for each option. | -| **title** | Heading text for each option. | -| **iconURL** | Sets the asset URL of the icon for each option. | -| **onClick** | Method to be invoked when user clicks on each option. | +| | | +| --- | --- | +| Type | `(conversation: CometChat.Conversation) => JSX.Element` | +| Default | Built-in subtitle | + +--- + +### textFormatters + +Custom text formatters for the conversation subtitle. + +| | | +| --- | --- | +| Type | `CometChatTextFormatter[]` | +| Default | Default formatters from data source | + +See [CometChatMentionsFormatter](/ui-kit/react/mentions-formatter-guide) for mention formatting. + +--- + +### titleView + +Custom renderer for the name / title text. + +| | | +| --- | --- | +| Type | `(conversation: CometChat.Conversation) => JSX.Element` | +| Default | Built-in title | + +--- + +### trailingView + +Custom renderer for the timestamp / badge / right section. + +| | | +| --- | --- | +| Type | `(conversation: CometChat.Conversation) => JSX.Element` | +| Default | Built-in trailing view | + +--- + +## Events + +| Event | Payload | Fires when | +| --- | --- | --- | +| `CometChatConversationEvents.ccConversationDeleted` | `CometChat.Conversation` | Conversation deleted from list | +| `CometChatConversationEvents.ccUpdateConversation` | `CometChat.Conversation` | Conversation updated | +| `CometChatConversationEvents.ccMarkConversationAsRead` | `CometChat.Conversation` | Conversation marked as read | + +All events are `Subject` from RxJS. Subscribe with `.subscribe()`, unsubscribe with the returned subscription's `.unsubscribe()`. + +--- -*** +## CSS Selectors + +| Target | Selector | +| --- | --- | +| Root | `.cometchat-conversations` | +| Header title | `.cometchat-conversations .cometchat-list__header-title` | +| List item | `.cometchat-conversations .cometchat-list-item` | +| Body title | `.cometchat-conversations .cometchat-list-item__body-title` | +| Avatar | `.cometchat-conversations .cometchat-avatar` | +| Avatar text | `.cometchat-conversations .cometchat-avatar__text` | +| Unread badge | `.cometchat-conversations .cometchat-badge` | +| Subtitle text | `.cometchat-conversations .cometchat-conversations__subtitle-text` | +| Subtitle sender | `.cometchat-conversations__subtitle-text-sender` | +| Status indicator (online) | `.cometchat-conversations__list-item-online .cometchat-list-item__status` | +| Group type (password) | `.cometchat-conversations__list-item-password .cometchat-list-item__status` | +| Group type (private) | `.cometchat-conversations__list-item-private .cometchat-list-item__status` | +| Read receipts | `.cometchat-conversations__subtitle-receipts-read` | +| Delivered receipts | `.cometchat-conversations__subtitle-receipts-delivered` | +| Sent receipts | `.cometchat-conversations__subtitle-receipts-sent` | +| Error receipts | `.cometchat-conversations__subtitle-receipts-error` | +| Active item | `.cometchat-conversations__list-item-active .cometchat-list-item` | +| Typing indicator | `.cometchat-conversations__subtitle-typing` | +| Trailing view | `.cometchat-conversations__trailing-view` | +| Badge count | `.cometchat-conversations__trailing-view-badge-count` | +| Empty state | `.cometchat-conversations__empty-state-view` | +| Error state | `.cometchat-conversations__error-state-view` | +| Shimmer loading | `.cometchat-conversations__shimmer` | +| Context menu | `.cometchat-conversations__trailing-view-options` | +| Mentions highlight | `.cometchat-conversations__subtitle-text .cometchat-mentions` | +| @you mentions | `.cometchat-conversations__subtitle-text .cometchat-mentions-you` | diff --git a/ui-kit/react/core-features.mdx b/ui-kit/react/core-features.mdx index 78a6de7de..296579438 100644 --- a/ui-kit/react/core-features.mdx +++ b/ui-kit/react/core-features.mdx @@ -1,12 +1,20 @@ --- title: "Core" +description: "Overview of CometChat's core chat features including instant messaging, media sharing, read receipts, typing indicators, user presence, reactions, mentions, threaded conversations, search, and moderation — with the UI Kit components that power each feature." --- -## Overview + +- **Package:** `@cometchat/chat-uikit-react` +- **Required setup:** `CometChatUIKit.init(UIKitSettings)` then `CometChatUIKit.login("UID")` — must complete before rendering any component +- **Core features:** Instant Messaging, Media Sharing, Read Receipts, Mark as Unread, Typing Indicator, User Presence, Reactions, Mentions, Quoted Reply, Search, Threaded Conversations, Moderation, Report Message, Group Chat +- **Key components:** `CometChatConversations` → [Conversations](/ui-kit/react/conversations), `CometChatMessageList` → [Message List](/ui-kit/react/message-list), `CometChatMessageComposer` → [Message Composer](/ui-kit/react/message-composer), `CometChatMessageHeader` → [Message Header](/ui-kit/react/message-header), `CometChatUsers` → [Users](/ui-kit/react/users), `CometChatGroups` → [Groups](/ui-kit/react/groups), `CometChatGroupMembers` → [Group Members](/ui-kit/react/group-members) +- **CSS class prefix:** `.cometchat-` +- **Theming:** Override CSS variables on `.cometchat` class. See [Theming](/ui-kit/react/theme) + -The UI Kit comprises a variety of components, each designed to work seamlessly with one another to deliver a comprehensive and intuitive chat experience. +## Overview -Here's how different UI Kit components work together to achieve CometChat's Core features: +The UI Kit components work together to deliver a complete chat experience. The sections below map each core feature to the components that power it. ## Instant Messaging @@ -23,7 +31,7 @@ At the heart of CometChat's functionality is the ability to support real-time te ## Media Sharing -Beyond text, CometChat allows users to share various media types within their conversations. This includes images, videos, audio files, and documents, enriching the chat experience and enabling more comprehensive communication. +CometChat supports sharing images, videos, audio files, and documents within conversations. @@ -86,7 +94,7 @@ CometChat's User Presence feature allows users to see whether their contacts are | --------------------------------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------- | | [Conversations](/ui-kit/react/conversations) | [Conversations](/ui-kit/react/conversations) is a component that renders conversation list item. Conversations item also shows user presence information. | | [Message Header](/ui-kit/react/message-header) | [Message Header](/ui-kit/react/message-header) that renders details of user/group. The Message Header also handles user presence information. | -| [Users](/ui-kit/react/users) | [Users](/ui-kit/react/users) renders list of users available in your app.It also responsible to render users presence information. | +| [Users](/ui-kit/react/users) | [Users](/ui-kit/react/users) renders the list of available users with presence information. | | [Group Members](/ui-kit/react/group-members) | [Group Members](/ui-kit/react/group-members) renders list of users available in the group. The Group Members component also handles user presence information. | ## Reactions @@ -115,45 +123,40 @@ Mentions is a robust feature provided by CometChat that enhances the interactivi | [Message Composer](/ui-kit/react/message-composer) | [Message Composer](/ui-kit/react/message-composer) is a component that allows users to craft and send various types of messages, including the usage of the mentions feature for direct addressing within the conversation. | | [Message List](/ui-kit/react/message-list) | [Message List](/ui-kit/react/message-list) is a component that displays a list of sent and received messages. It also supports the rendering of Mentions, enhancing the readability and interactivity of conversations. | -## Quoted Reply +## Threaded Conversations -Quoted Reply is a robust feature provided by CometChat that enables users to quickly reply to specific messages by selecting the "Reply" option from a message's action menu. This enhances context, keeps conversations organized, and improves overall chat experience in both 1-1 and group chats. +The Threaded Conversations feature enables users to respond directly to a specific message in a chat. This keeps conversations organized and enhances the user experience by maintaining context, especially in group chats. - + -| Components | Functionality | -| ------------------------------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | -| [Message List](/ui-kit/react/message-list) | [Message List](/ui-kit/react/message-list) supports replying to messages via the "Reply" option. Users can select "Reply" on a message to open the composer with the quoted reply pre-filled, maintaining context. | -| [Message Composer](/ui-kit/react/message-composer) | [Message Composer](/ui-kit/react/message-composer) works seamlessly with Quoted Message by showing the quoted reply above the input field, letting users compose their response in proper context. | +| Components | Functionality | +| ----------------------------------------------------------------------- | ----------------------------------------------------------------------------------------------------------------------------------------------- | +| [Threaded Message Preview](/ui-kit/react/threaded-message-preview) | [Threaded Message Preview](/ui-kit/react/threaded-message-preview) component displays the parent message along with the number of replies. | -## Conversation and Advanced Search +## Quoted Replies -Conversation and Advanced Search is a powerful feature provided by CometChat that enables users to quickly find conversations, messages, and media across chats in real time. It supports filters, scopes, and custom actions, allowing users to locate content efficiently while keeping the chat experience smooth and intuitive. +Quoted Replies is a robust feature provided by CometChat that enables users to quickly reply to specific messages by selecting the "Reply" option from a message's action menu. This enhances context, keeps conversations organized, and improves overall chat experience in both 1-1 and group chats. - + | Components | Functionality | | ------------------------------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | -| [Search](/ui-kit/react/search) | [Search](/ui-kit/react/search) allows users to search across conversations and messages in real time. Users can click on a result to open the conversation or jump directly to a specific message. | -| [Message Header](/ui-kit/react/message-header) | [Message Header](/ui-kit/react/message-header) shows the search button in the chat header, allowing users to search within a conversation. | -| [Message List](/ui-kit/react/message-list) | [Message List](/ui-kit/react/message-list) shows the selected message when clicked from search results and highlights it in the message list. | -| [Conversations](/ui-kit/react/conversations) | [Conversations](/ui-kit/react/conversations) displays the search input. | +| [Message List](/ui-kit/react/message-list) | [Message List](/ui-kit/react/message-list) supports replying to messages via the "Reply" option. Users can select "Reply" on a message to open the composer with the quoted reply pre-filled, maintaining context. | +| [Message Composer](/ui-kit/react/message-composer) | [Message Composer](/ui-kit/react/message-composer) shows the quoted reply above the input field, providing context for the response. | -## Threaded Conversations +## Group Chat -The Threaded Conversations feature enables users to respond directly to a specific message in a chat. This keeps conversations organized and enhances the user experience by maintaining context, especially in group chats. +CometChat facilitates Group Chats, allowing users to have conversations with multiple participants simultaneously. This feature is crucial for team collaborations, group discussions, social communities, and more. - + -| Components | Functionality | -| ----------------------------------------------------------------------- | ----------------------------------------------------------------------------------------------------------------------------------------------- | -| [Threaded Message Preview](/ui-kit/react/threaded-message-preview) | [Threaded Message Preview](/ui-kit/react/threaded-message-preview) component displays the parent message along with the number of replies. | +See the [Groups](/ui-kit/react/groups) component page for details. ## Moderation @@ -169,9 +172,9 @@ Learn more about setting up moderation rules and managing content in the [Modera | Components | Functionality | | ----------------------------------------------- | -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | -| [Message List](/ui-kit/react/message-list) | [Message List](/ui-kit/react/message-list) automatically handles moderated messages, displaying blocked content appropriately based on your moderation settings. | +| [Message List](/ui-kit/react/message-list) | [Message List](/ui-kit/react/message-list) automatically handles moderated messages, displaying blocked content based on moderation settings. | -After implementing moderation rules, users can report messages they find inappropriate or harmful. As a next step, you can enable the **[Report Message](#report-message)** feature to allow users to flag messages for review by moderators. +The **[Report Message](#report-message)** feature enables users to flag messages for review by moderators. ## Report Message @@ -189,12 +192,37 @@ Learn more about how flagged messages are handled, reviewed, and moderated in th | ----------------------------------------------- | -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | | [Message List](/ui-kit/react/message-list) | [Message List](/ui-kit/react/message-list) provides the "Report Message" option in the message actions menu, allowing users to initiate the reporting process for inappropriate messages. | -## Group Chat +## Conversation and Advanced Search -CometChat facilitates Group Chats, allowing users to have conversations with multiple participants simultaneously. This feature is crucial for team collaborations, group discussions, social communities, and more. +Conversation and Advanced Search is a powerful feature provided by CometChat that enables users to quickly find conversations, messages, and media across chats in real time. It supports filters, scopes, and custom actions, allowing users to locate content efficiently while keeping the chat experience smooth and intuitive. - + -For a comprehensive understanding and guide on implementing and using the Groups feature in CometChat, you should refer to our detailed guide on [Groups](/ui-kit/react/groups). +| Components | Functionality | +| ------------------------------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | +| [Search](/ui-kit/react/search) | [Search](/ui-kit/react/search) allows users to search across conversations and messages in real time. Users can click on a result to open the conversation or jump directly to a specific message. | +| [Message Header](/ui-kit/react/message-header) | [Message Header](/ui-kit/react/message-header) shows the search button in the chat header, allowing users to search within a conversation. | +| [Message List](/ui-kit/react/message-list) | [Message List](/ui-kit/react/message-list) shows the selected message when clicked from search results and highlights it in the message list. | +| [Conversations](/ui-kit/react/conversations) | [Conversations](/ui-kit/react/conversations) displays the search input. | + +See the [Groups](/ui-kit/react/groups) component page for details. +--- + +## Next Steps + + + + Browse all available UI Kit components + + + Customize the look and feel of your chat UI + + + Add audio and video calling + + + Explore AI-powered chat capabilities + + diff --git a/ui-kit/react/custom-text-formatter-guide.mdx b/ui-kit/react/custom-text-formatter-guide.mdx index eadbdc933..6a5ea3fa1 100644 --- a/ui-kit/react/custom-text-formatter-guide.mdx +++ b/ui-kit/react/custom-text-formatter-guide.mdx @@ -1,7 +1,19 @@ --- title: "Custom Text Formatter" +description: "Extend the CometChatTextFormatter base class to implement custom inline text patterns with regex and callbacks." --- + +- **Package:** `@cometchat/chat-uikit-react` +- **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, input field integration, key event callbacks +- **Sample app:** [GitHub](https://github.com/cometchat/cometchat-uikit-react/tree/v6/sample-app) +- **Related:** [ShortCut Formatter](/ui-kit/react/shortcut-formatter-guide) | [Mentions Formatter](/ui-kit/react/mentions-formatter-guide) | [All Guides](/ui-kit/react/guide-overview) + + + ## Overview You can create your custom text formatter for CometChat using the `CometChatTextFormatter`. `CometChatTextFormatter` is an abstract utility class that serves as a foundational structure for enabling text formatting in the message composer and text message bubbles. It can be extended to create custom formatter classes, tailored to suit specific application needs, making it a valuable tool for text customization and enhancement in chat interfaces. @@ -73,7 +85,7 @@ Below is an example demonstrating how to use a custom formatter class in compone -```ts +```ts lines import { CometChatTextFormatter } from "@cometchat/chat-uikit-react"; class HashTagTextFormatter extends CometChatTextFormatter { @@ -227,7 +239,7 @@ export default HashTagTextFormatter; -```tsx +```tsx lines import { HashTagTextFormatter } from "./HashTagTextFormatter"; export default function MessageListDemo() { @@ -288,7 +300,7 @@ Upon calling `reRender`, the composer will invoke the `getFormattedText` functio -```js +```js lines /** * If the input text is provided, it returns the formatted text. Otherwise, it edits the text using the current cursor position. * @param {string|null} inputText - The text to format. @@ -306,7 +318,7 @@ Upon calling `reRender`, the composer will invoke the `getFormattedText` functio -```js +```js lines /** * Handles 'keydown' events. * @param {KeyboardEvent} event - The keyboard event. @@ -325,7 +337,7 @@ onKeyUp(event: KeyboardEvent) { -```js +```js lines /** * Handles 'keydown' events. * @param {KeyboardEvent} event - The keyboard event. @@ -336,7 +348,7 @@ onKeyDown(event: KeyboardEvent) {} -```js +```js lines /** * Composer and Text Bubbles will call this function when rendering the HTML content. * This will be called for each HTML Element present in the formatted string. @@ -407,7 +419,7 @@ registerEventListeners(element: HTMLElement, domTokenList: DOMTokenList) { -```js +```js lines /** * Returns the original unformatted text from the input text. * @param {string|null|undefined} inputText - The input text to get original text from. @@ -433,4 +445,21 @@ registerEventListeners(element: HTMLElement, domTokenList: DOMTokenList) { - \ No newline at end of file + + +## Next Steps + + + + Add @mentions with styled tokens. + + + Customize the message input component. + + + Browse all feature and formatter guides. + + + Full working sample application on GitHub. + + diff --git a/ui-kit/react/events.mdx b/ui-kit/react/events.mdx index 0ba3e00fc..5444eefa6 100644 --- a/ui-kit/react/events.mdx +++ b/ui-kit/react/events.mdx @@ -1,96 +1,100 @@ --- title: "Events" +description: "Reference for CometChat React UI Kit events including conversation, user, group, message, and call events." --- -## Overview + + +| Field | Value | +| --- | --- | +| Package | `@cometchat/chat-uikit-react` | +| Conversation events | `ccConversationDeleted`, `ccUpdateConversation` | +| User events | `ccUserBlocked`, `ccUserUnblocked` | +| Group events | `ccGroupCreated`, `ccGroupDeleted`, `ccGroupLeft`, `ccGroupMemberScopeChanged`, `ccGroupMemberKicked`, `ccGroupMemberBanned`, `ccGroupMemberUnbanned`, `ccGroupMemberJoined`, `ccGroupMemberAdded`, `ccOwnershipChanged` | +| Message events | `ccMessageSent`, `ccMessageEdited`, `ccReplyToMessage`, `ccMessageDeleted`, `ccMessageRead`, `ccLiveReaction`, plus SDK listener events | +| Call events | `ccOutgoingCall`, `ccCallAccepted`, `ccCallRejected`, `ccCallEnded` | +| UI events | `ccActiveChatChanged` | +| Purpose | Decoupled communication between UI Kit components — subscribe to events to react to changes without direct component references | -Events allow for a decoupled, flexible architecture where different parts of the application can interact without having to directly reference each other. This makes it easier to create complex, interactive experiences, as well as to extend and customize the functionality provided by the CometChat UI Kit. + -All components have the ability to emit events. These events are dispatched in response to certain changes or user interactions within the component. By emitting events, these components allow other parts of the application to react to changes or interactions, thus enabling dynamic and interactive behavior within the application. +## Overview + +Events provide decoupled communication between UI Kit components. Components emit events in response to user interactions or state changes, allowing other parts of the application to react without direct component references. ### CometChatConversationEvents -`CometChatConversationEvents` emits events when the logged-in user executes some action on a conversation object. +`CometChatConversationEvents` emits events when the logged-in user acts on a conversation object. | Name | Description | | ------------------------- | ------------------------------------------------------------------------------------------------ | -| ccConversationDeleted | This event is triggered when the user successfully deletes a conversation. | -| ccUpdateConversation | This event is triggered to update a conversation in the conversation list. Takes a Conversation object to update. | +| **ccConversationDeleted** | This event is triggered when the user successfully deletes a conversation. | +| **ccUpdateConversation** | This event is triggered to update a conversation in the conversation list. Takes a Conversation object to update. | ### CometChatUserEvents -`CometChatUserEvents` emits events when the logged-in user executes some action on an user object. - -It consists of the following events: +`CometChatUserEvents` emits events when the logged-in user acts on another user object. | Name | Description | | --------------- | ------------------------------------------------------------------------- | -| ccUserBlocked | This event is triggered when the user successfully blocks another user. | -| ccUserUnblocked | This event is triggered when the user successfully unblocks another user. | +| **ccUserBlocked** | This event is triggered when the user successfully blocks another user. | +| **ccUserUnblocked** | This event is triggered when the user successfully unblocks another user. | ### CometChatGroupEvents -`CometChatGroupEvents` emits events when the logged-in user executes some action on a group object. - -It consists of the following events: +`CometChatGroupEvents` emits events when the logged-in user acts on a group object. | Name | Description | | ------------------------- | ------------------------------------------------------------------------------------ | -| ccGroupCreated | This event is triggered when the user creates a group successfully | -| ccGroupDeleted | This event is triggered when the group member deletes the group successfully | -| ccGroupLeft | This event is triggered when the group member leaves the group successfully | -| ccGroupMemberScopeChanged | This event is triggered when the group member's scope is updated successfully | -| ccGroupMemberKicked | This event is triggered when the group member is kicked | -| ccGroupMemberBanned | This event is triggered when the group member is banned | -| ccGroupMemberUnbanned | This event is triggered when the group member is un-banned | -| ccGroupMemberJoined | This event is triggered when a user joins the group | -| ccGroupMemberAdded | This event is triggered when a user is added to the group | -| ccOwnershipChanged | This event is triggered when the group ownership is assigned to another group member | +| **ccGroupCreated** | This event is triggered when the user creates a group successfully | +| **ccGroupDeleted** | This event is triggered when the group member deletes the group successfully | +| **ccGroupLeft** | This event is triggered when the group member leaves the group successfully | +| **ccGroupMemberScopeChanged** | This event is triggered when the group member's scope is updated successfully | +| **ccGroupMemberKicked** | This event is triggered when the group member is kicked | +| **ccGroupMemberBanned** | This event is triggered when the group member is banned | +| **ccGroupMemberUnbanned** | This event is triggered when the group member is un-banned | +| **ccGroupMemberJoined** | This event is triggered when a user joins the group | +| **ccGroupMemberAdded** | This event is triggered when a user is added to the group | +| **ccOwnershipChanged** | This event is triggered when the group ownership is assigned to another group member | ### CometChatMessageEvents -`CometChatMessageEvents` emits events when the logged-in user executes some action on a message object. - -It consists of the following events: +`CometChatMessageEvents` emits events when the logged-in user acts on a message object. | Name | Description | | -------------------------- | --------------------------------------------------------------------------------------------------------- | -| ccMessageSent | This event is triggered when the sent message is in transit and also when it is received by the receiver. | -| ccMessageEdited | This event is triggered when the user successfully edits the message. | -| ccReplyToMessage | This event is triggered when the user successfully replies to a message. | -| ccMessageDeleted | This event is triggered when the user successfully deletes the message. | -| ccMessageRead | This event is triggered when the sent message is read by the receiver. | -| ccLiveReaction | This event is triggered when the user sends a live reaction. | -| onTextMessageReceived | This event is emitted when the CometChat SDK listener emits a text message. | -| onMediaMessageReceived | This event is emitted when the CometChat SDK listener emits a media message. | -| onCustomMessageReceived | This event is emitted when the CometChat SDK listener emits a custom message. | -| onTypingStarted | This event is emitted when the CometChat SDK listener indicates that a user has started typing. | -| onTypingEnded | This event is emitted when the CometChat SDK listener indicates that a user has stopped typing. | -| onMessagesDelivered | This event is emitted when the CometChat SDK listener indicates that messages have been delivered. | -| onMessagesRead | This event is emitted when the CometChat SDK listener indicates that messages have been read. | -| onMessageEdited | This event is emitted when the CometChat SDK listener indicates that a message has been edited. | -| onMessageDeleted | This event is emitted when the CometChat SDK listener indicates that a message has been deleted. | -| onTransientMessageReceived | This event is emitted when the CometChat SDK listener emits a transient message. | +| **ccMessageSent** | This event is triggered when the sent message is in transit and also when it is received by the receiver. | +| **ccMessageEdited** | This event is triggered when the user successfully edits the message. | +| **ccReplyToMessage** | This event is triggered when the user successfully replies to a message. | +| **ccMessageDeleted** | This event is triggered when the user successfully deletes the message. | +| **ccMessageRead** | This event is triggered when the sent message is read by the receiver. | +| **ccLiveReaction** | This event is triggered when the user sends a live reaction. | +| **onTextMessageReceived** | This event is emitted when the CometChat SDK listener emits a text message. | +| **onMediaMessageReceived** | This event is emitted when the CometChat SDK listener emits a media message. | +| **onCustomMessageReceived** | This event is emitted when the CometChat SDK listener emits a custom message. | +| **onTypingStarted** | This event is emitted when the CometChat SDK listener indicates that a user has started typing. | +| **onTypingEnded** | This event is emitted when the CometChat SDK listener indicates that a user has stopped typing. | +| **onMessagesDelivered** | This event is emitted when the CometChat SDK listener indicates that messages have been delivered. | +| **onMessagesRead** | This event is emitted when the CometChat SDK listener indicates that messages have been read. | +| **onMessageEdited** | This event is emitted when the CometChat SDK listener indicates that a message has been edited. | +| **onMessageDeleted** | This event is emitted when the CometChat SDK listener indicates that a message has been deleted. | +| **onTransientMessageReceived** | This event is emitted when the CometChat SDK listener emits a transient message. | ### CometChatCallEvents -`CometChatCallEvents` emits events when the logged-in user executes some action on a call object. - -It consists of the following events: +`CometChatCallEvents` emits events when the logged-in user acts on a call object. | Name | Description | | -------------- | ---------------------------------------------------------------------------- | -| ccOutgoingCall | This event is triggered when the user initiates a voice/video call. | -| ccCallAccepted | This event is triggered when the initiated call is accepted by the receiver. | -| ccCallRejected | This event is triggered when the initiated call is rejected by the receiver. | -| ccCallEnded | This event is triggered when the initiated call successfully ends. | +| **ccOutgoingCall** | This event is triggered when the user initiates a voice/video call. | +| **ccCallAccepted** | This event is triggered when the initiated call is accepted by the receiver. | +| **ccCallRejected** | This event is triggered when the initiated call is rejected by the receiver. | +| **ccCallEnded** | This event is triggered when the initiated call successfully ends. | ### UI events -UI events, refer to actions or interactions performed by a user within the CometChat's UI Kit. These events are triggered when a user interacts with various UI elements, such as buttons, menus, checkboxes, input fields, or any other interactive components. - -It consists of the following events: +UI events are triggered when a user interacts with UI Kit elements such as buttons, menus, or input fields. | Name | Description | | ------------------- | ---------------------------------------------------------------------------- | -| ccActiveChatChanged | This event is triggered when the user navigates to a particular chat window. | +| **ccActiveChatChanged** | This event is triggered when the user navigates to a particular chat window. | diff --git a/ui-kit/react/extensions.mdx b/ui-kit/react/extensions.mdx index 15f4332d9..267c1d403 100644 --- a/ui-kit/react/extensions.mdx +++ b/ui-kit/react/extensions.mdx @@ -1,87 +1,193 @@ --- title: "Extensions" +description: "Overview of CometChat's extensions grouped by Dashboard categories (User Experience, User Engagement, Collaboration, Security, Customer Support, Smart Chat Features) and how they auto-integrate into React UI Kit components." --- + +- **Package:** `@cometchat/chat-uikit-react` +- **Required setup:** `CometChatUIKit.init(UIKitSettings)` then `CometChatUIKit.login("UID")` + Extensions enabled in [CometChat Dashboard](/fundamentals/extensions-overview) +- **Extension categories:** User Experience, User Engagement, Collaboration, Security, Customer Support, Smart Chat Features +- **Key components:** `CometChatMessageComposer` → [Message Composer](/ui-kit/react/message-composer) (Stickers, Polls, Whiteboard, Document), `CometChatMessageList` → [Message List](/ui-kit/react/message-list) (Translation, Link Preview, Thumbnails) +- **Activation:** Enable each extension from the CometChat Dashboard — UI Kit auto-integrates them, no additional code required + + ## Overview -CometChat's UI Kit offers built-in support for various extensions, enriching the chatting experience with enhanced functionality. These extensions augment your chat application, making it more interactive, secure, and efficient. +CometChat UI Kit includes built-in support for extensions that add interactive, secure, and efficient features to chat. Extensions are activated from the [CometChat Dashboard](/fundamentals/extensions-overview) and auto-integrate into UI Kit components on init and login. + + +Ensure `CometChatUIKit.init(UIKitSettings)` has completed and the user is logged in via `CometChatUIKit.login("UID")`. Extensions must be activated from the [CometChat Dashboard](/fundamentals/extensions-overview). + -Activating extensions within CometChat is a straightforward process through your application's dashboard. For detailed instructions, refer to our guide on [Extensions](/fundamentals/extensions-overview). +## Built-in Extensions -Once you've enabled your desired extension in the dashboard, it seamlessly integrates into your CometChat application upon initialization and successful login. It's important to note that extension features will only be available if they are supported by the CometChat UI Kit. +The grouping below mirrors the CometChat Dashboard. -CometChat's UI Kit provides native support for 12 powerful extensions. This effortless integration enables you to enhance your chat application with engaging features without any additional coding. Simply enable the desired extensions from the CometChat Dashboard, and they will automatically enhance the relevant components of your application, providing a richer and more engaging experience for your users. +### User Experience -## Built-in Extensions +#### Bitly -Here's a guide on how you can enable and integrate these extensions: +Shortens long URLs in text messages using Bitly. See [Bitly Extension](/fundamentals/bitly). -### Stickers +#### Link Preview -The Stickers extension allows users to express their emotions more creatively. It adds a much-needed fun element to the chat by allowing users to send various pre-designed stickers. For a comprehensive understanding and guide on implementing and using the Sticker Extension, refer to our specific guide on the [Sticker Extension](/fundamentals/stickers). +Displays a summary (title, description, thumbnail) for URLs shared in chat. See [Link Preview Extension](/fundamentals/link-preview). -Once you have successfully activated the [Sticker Extension](/fundamentals/stickers) from your CometChat Dashboard, the feature will automatically be incorporated into the [Message Composer](/ui-kit/react/message-composer) component of UI Kits. +Auto-integrates into the Message Bubble of [MessageList](/ui-kit/react/message-list) when activated. - + -### Polls +#### Message Shortcuts + +Sends predefined messages using short codes (e.g., `!hb` expands to `Happy birthday!`). See [Message Shortcuts Extension](/fundamentals/message-shortcuts). + +#### Pin Message -The Polls extension enhances group discussions by allowing users to create polls. Users can ask questions with a predefined list of answers, enabling a quick, organized way to gather group opinions. For a comprehensive understanding and guide on implementing and using the Polls Extension, refer to our specific guide on the [Polls Extension](/fundamentals/polls). +Pins important messages in a conversation for easy access. See [Pin Message Extension](/fundamentals/pin-message). -Once you have successfully activated the [Polls Extension](/fundamentals/polls) from your CometChat Dashboard, the feature will automatically be incorporated into the Action Sheet of the [Message Composer](/ui-kit/react/message-composer) component of UI Kits. +#### Rich Media Preview + +Generates rich preview panels for URLs using iFramely. See [Rich Media Preview Extension](/fundamentals/rich-media-preview). + +#### Save Message + +Bookmarks messages for later reference. Saved messages are private to the user. See [Save Message Extension](/fundamentals/save-message). + +#### Thumbnail Generation + +Creates smaller preview images for shared images, reducing bandwidth. See [Thumbnail Generation Extension](/fundamentals/thumbnail-generation). + +Auto-integrates into the Message Bubble of [MessageList](/ui-kit/react/message-list) when activated. - + -### Collaborative Whiteboard +#### TinyURL + +URL shortening using TinyURL. See [TinyURL Extension](/fundamentals/tinyurl). + +#### Voice Transcription + +Converts audio messages to text. See [Voice Transcription Extension](/fundamentals/voice-transcription). + +### User Engagement + +#### Giphy + +Search and share GIFs from Giphy. See [Giphy Extension](/fundamentals/giphy). -The Collaborative Whiteboard extension facilitates real-time collaboration. Users can draw, brainstorm, and share ideas on a shared digital whiteboard. For a comprehensive understanding and guide on implementing and using the Collaborative Whiteboard Extension, refer to our specific guide on the [Collaborative Whiteboard Extension](/fundamentals/collaborative-whiteboard). +#### Message Translation -Once you have successfully activated the [Collaborative Whiteboard Extension](/fundamentals/collaborative-whiteboard) from your CometChat Dashboard, the feature will automatically be incorporated into the Action Sheet of the [Message Composer](/ui-kit/react/message-composer) component of UI Kits. +Translates messages into the local locale. See [Message Translation Extension](/fundamentals/message-translation). + +Auto-integrates into the Action Sheet of [MessageList](/ui-kit/react/message-list) when activated. - + -### Collaborative Document +#### Polls -With the Collaborative Document extension, users can work together on a shared document. This feature is essential for remote teams where document collaboration is a recurring requirement. For a comprehensive understanding and guide on implementing and using the Collaborative Document Extension, refer to our specific guide on the [Collaborative Document Extension](/fundamentals/collaborative-document). +Creates polls in group discussions with predefined answer options. See [Polls Extension](/fundamentals/polls). -Once you have successfully activated the [Collaborative Document Extension](/fundamentals/collaborative-document) from your CometChat Dashboard, the feature will automatically be incorporated into the Action Sheet of the [Message Composer](/ui-kit/react/message-composer) component of UI Kits. +Auto-integrates into the Action Sheet of [Message Composer](/ui-kit/react/message-composer) when activated. - + -### Message Translation +#### Reminders + +Sets reminders for messages or creates personal reminders. A bot sends a notification when due. See [Reminders Extension](/fundamentals/reminders). + +#### Stickers -The Message Translation extension in CometChat is designed to translate any message into your local locale. It eliminates language barriers, making the chat more inclusive. For a comprehensive understanding and guide on implementing and using the Message Translation Extension, refer to our specific guide on the [Message Translation Extension](/fundamentals/message-translation). +Sends pre-designed stickers in chat. See [Sticker Extension](/fundamentals/stickers). -Once you have successfully activated the [Message Translation Extension](/fundamentals/message-translation) from your CometChat Dashboard, the feature will automatically be incorporated into the Action Sheet of [MessageList Component](/ui-kit/react/message-list) component of UI Kits. +Auto-integrates into [Message Composer](/ui-kit/react/message-composer) when activated. - + -### Link Preview +#### Stipop + +Integrates Stipop's sticker library. See [Stipop Extension](/fundamentals/stickers-stipop). + +#### Tenor -The Link Preview extension provides a summary of the URL shared in the chat. It includes the title, a description, and a thumbnail image from the web page. For a comprehensive understanding and guide on implementing and using the Link Preview Extension, refer to our specific guide on the [Link Preview Extension](/fundamentals/link-preview). +Search and share GIFs from Tenor. See [Tenor Extension](/fundamentals/tenor). -Once you have successfully activated the [Link Preview Extension](/fundamentals/link-preview) from your CometChat Dashboard, the feature will automatically be incorporated into the Message Bubble of [MessageList Component](/ui-kit/react/message-list) component of UI Kits. +### Collaboration + +#### Collaborative Document + +Shared document editing for real-time collaboration. See [Collaborative Document Extension](/fundamentals/collaborative-document). + +Auto-integrates into the Action Sheet of [Message Composer](/ui-kit/react/message-composer) when activated. - + -### Thumbnail Generation +#### Collaborative Whiteboard -The Thumbnail Generation extension automatically creates a smaller preview image whenever a larger image is shared, helping to reduce the upload/download time and bandwidth usage. For a comprehensive understanding and guide on implementing and using the Thumbnail Generation Extension, refer to our specific guide on the [Thumbnail Generation Extension](/fundamentals/thumbnail-generation). +Real-time shared whiteboard for drawing and brainstorming. See [Collaborative Whiteboard Extension](/fundamentals/collaborative-whiteboard). -Once you have successfully activated the [Thumbnail Generation Extension](/fundamentals/thumbnail-generation) from your CometChat Dashboard, the feature will automatically be incorporated into the Message Bubble of [MessageList Component](/ui-kit/react/message-list) component of UI Kits. +Auto-integrates into the Action Sheet of [Message Composer](/ui-kit/react/message-composer) when activated. - + + +### Security + +#### Disappearing Messages + +Messages auto-delete after a specified interval. Works for 1:1 and group messages. See [Disappearing Messages Extension](/fundamentals/disappearing-messages). + +### Customer Support + +#### Chatwoot + +Routes user messages to Chatwoot for customer support. See [Chatwoot Extension](/fundamentals/chatwoot). + +#### Intercom + +Integrates Intercom for in-app customer support. See [Intercom Extension](/fundamentals/intercom). + +### Smart Chat Features + +#### Conversation Starter + +AI-generated opening messages for new chats. See [Conversation Starter](/fundamentals/ai-user-copilot/conversation-starter) and [AI Features](/ui-kit/react/ai-features). + +#### Smart Replies + +AI-generated response suggestions based on conversation context. See [Smart Replies](/fundamentals/ai-user-copilot/smart-replies) and [AI Features](/ui-kit/react/ai-features). + +#### Conversation Summary + +AI-generated recap of long conversations. See [Conversation Summary](/fundamentals/ai-user-copilot/conversation-summary) and [AI Features](/ui-kit/react/ai-features). + +--- + +## Next Steps + + + + Customize the composer where most extensions appear + + + Customize the message list for extension-rendered content + + + Core chat features like messaging and reactions + + + AI-powered chat capabilities + + diff --git a/ui-kit/react/group-members.mdx b/ui-kit/react/group-members.mdx index ce7ec270f..1f0f17cc1 100644 --- a/ui-kit/react/group-members.mdx +++ b/ui-kit/react/group-members.mdx @@ -1,658 +1,814 @@ --- title: "Group Members" +description: "Scrollable, searchable list of members in a specific group with roles, scopes, online status, and member management actions." --- + +```json +{ + "component": "CometChatGroupMembers", + "package": "@cometchat/chat-uikit-react", + "import": "import { CometChatGroupMembers } from \"@cometchat/chat-uikit-react\";", + "cssImport": "import \"@cometchat/chat-uikit-react/css-variables.css\";", + "description": "Scrollable, searchable list of members in a specific group with roles, scopes, online status, and member management actions.", + "cssRootClass": ".cometchat-group-members", + "primaryOutput": { + "prop": "onItemClick", + "type": "(groupMember: CometChat.GroupMember) => void" + }, + "props": { + "data": { + "group": { + "type": "CometChat.Group", + "required": true, + "note": "The group whose members are displayed" + }, + "groupMemberRequestBuilder": { + "type": "CometChat.GroupMembersRequestBuilder", + "default": "SDK default (30 per page)", + "note": "Pass the builder, not the result of .build()" + }, + "searchRequestBuilder": { + "type": "CometChat.GroupMembersRequestBuilder", + "default": "undefined" + }, + "searchKeyword": { + "type": "string", + "default": "\"\"" + } + }, + "callbacks": { + "onItemClick": "(groupMember: CometChat.GroupMember) => void", + "onSelect": "(groupMember: CometChat.GroupMember, selected: boolean) => void", + "onEmpty": "() => void", + "onError": "((error: CometChat.CometChatException) => void) | null" + }, + "visibility": { + "hideSearch": { "type": "boolean", "default": false }, + "hideError": { "type": "boolean", "default": false }, + "hideKickMemberOption": { "type": "boolean", "default": false }, + "hideBanMemberOption": { "type": "boolean", "default": false }, + "hideScopeChangeOption": { "type": "boolean", "default": false }, + "hideUserStatus": { "type": "boolean", "default": false }, + "disableLoadingState": { "type": "boolean", "default": false }, + "showScrollbar": { "type": "boolean", "default": false } + }, + "selection": { + "selectionMode": { + "type": "SelectionMode", + "values": ["SelectionMode.single (0)", "SelectionMode.multiple (1)", "SelectionMode.none (2)"], + "default": "SelectionMode.none" + } + }, + "viewSlots": { + "itemView": "(groupMember: CometChat.GroupMember) => JSX.Element", + "leadingView": "(groupMember: CometChat.GroupMember) => JSX.Element", + "titleView": "(groupMember: CometChat.GroupMember) => JSX.Element", + "subtitleView": "(groupMember: CometChat.GroupMember) => JSX.Element", + "trailingView": "(groupMember: CometChat.GroupMember) => JSX.Element", + "headerView": "JSX.Element", + "loadingView": "JSX.Element", + "emptyView": "JSX.Element", + "errorView": "JSX.Element", + "options": "(group: CometChat.Group, groupMember: CometChat.GroupMember) => CometChatOption[]" + } + }, + "events": [ + { + "name": "CometChatGroupEvents.ccGroupMemberKicked", + "payload": "IGroupMemberKickedBanned", + "description": "Member kicked" + }, + { + "name": "CometChatGroupEvents.ccGroupMemberBanned", + "payload": "IGroupMemberKickedBanned", + "description": "Member banned" + }, + { + "name": "CometChatGroupEvents.ccGroupMemberScopeChanged", + "payload": "IGroupMemberScopeChanged", + "description": "Member scope changed" + }, + { + "name": "CometChatGroupEvents.ccGroupMemberAdded", + "payload": "IGroupMemberAdded", + "description": "Members added" + } + ], + "sdkListeners": [ + "onGroupMemberScopeChanged", + "onGroupMemberKicked", + "onGroupMemberBanned", + "onMemberAddedToGroup", + "onGroupMemberLeft", + "onGroupMemberJoined", + "onUserOnline", + "onUserOffline" + ], + "types": { + "CometChatOption": { + "id": "string | undefined", + "title": "string | undefined", + "iconURL": "string | undefined", + "onClick": "(() => void) | undefined" + }, + "SelectionMode": { + "single": 0, + "multiple": 1, + "none": 2 + } + } +} +``` + + +## Where It Fits + +`CometChatGroupMembers` is a panel component that renders the member list for a specific group. It requires a `group` prop and provides built-in member management actions (kick, ban, scope change) based on the logged-in user's role. Typically rendered alongside the message view in a group chat layout. + +```tsx +import { useEffect, useState } from "react"; +import { + CometChatGroupMembers, + CometChatMessageHeader, + CometChatMessageList, + CometChatMessageComposer, +} from "@cometchat/chat-uikit-react"; +import { CometChat } from "@cometchat/chat-sdk-javascript"; +import "@cometchat/chat-uikit-react/css-variables.css"; + +function GroupChatWithMembers() { + const [group, setGroup] = useState(); -## Overview + useEffect(() => { + CometChat.getGroup("GROUP_GUID").then(setGroup); + }, []); -`CometChatGroupMembers` is a Component that displays all users added or invited to a group, granting them access to group discussions, shared content, and collaborative features. Group members can communicate in real-time via messaging, voice and video calls, and other activities. They can interact, share files, and join calls based on group permissions set by the administrator or owner. + if (!group) return null; + + return ( +
+
+ +
+
+ + + +
+
+ ); +} +``` -*** - -## Usage - -### Integration +--- -The following code snippet illustrates how you can directly incorporate the Group Members component into your Application. +## Minimal Render - - ```tsx -import { CometChat } from "@cometchat/chat-sdk-javascript"; +import { useEffect, useState } from "react"; import { CometChatGroupMembers } from "@cometchat/chat-uikit-react"; -import React from "react"; +import { CometChat } from "@cometchat/chat-sdk-javascript"; +import "@cometchat/chat-uikit-react/css-variables.css"; -const GroupMembersDemo = () => { - const [chatGroup, setChatGroup] = React.useState(); +function GroupMembersDemo() { + const [group, setGroup] = useState(); - React.useEffect(() => { - CometChat.getGroup("guid").then((group) => { - setChatGroup(group); - }); + useEffect(() => { + CometChat.getGroup("GROUP_GUID").then(setGroup); }, []); - return <>{chatGroup && }; -}; + return group ? ( +
+ +
+ ) : null; +} export default GroupMembersDemo; ``` -
+Root CSS class: `.cometchat-group-members` + +--- + +## Filtering Group Members + +Pass a `CometChat.GroupMembersRequestBuilder` to `groupMemberRequestBuilder`. Pass the builder instance — not the result of `.build()`. - ```tsx -import { GroupMembersDemo } from "./GroupMembersDemo"; +import { CometChatGroupMembers } from "@cometchat/chat-uikit-react"; +import { CometChat } from "@cometchat/chat-sdk-javascript"; -export default function App() { +function FilteredGroupMembers({ group }: { group: CometChat.Group }) { return ( -
- -
+ ); } ``` -
- -
+### Filter Recipes -*** +| Recipe | Code | +| --- | --- | +| Limit to 10 per page | `new CometChat.GroupMembersRequestBuilder("GUID").setLimit(10)` | +| Search by keyword | `new CometChat.GroupMembersRequestBuilder("GUID").setSearchKeyword("john")` | +| Admins and moderators only | `new CometChat.GroupMembersRequestBuilder("GUID").setScopes(["admin", "moderator"])` | -### Actions +Default page size is 30. The component uses infinite scroll — the next page loads as the user scrolls to the bottom. -[Actions](/ui-kit/react/components-overview#actions) dictate how a component functions. They are divided into two types: Predefined and User-defined. You can override either type, allowing you to tailor the behavior of the component to fit your specific needs. +The `searchRequestBuilder` prop accepts a separate `GroupMembersRequestBuilder` for filtering when the search bar is active. -##### 1. onSelect +Refer to [GroupMembersRequestBuilder](/sdk/javascript/retrieve-group-members) for the full builder API. -The `onSelect` action is activated when you select the done icon while in selection mode. This returns a list of all the group members that you have selected. +--- -This action does not come with any predefined behavior. However, you have the flexibility to override this event and tailor it to suit your needs using the following code snippet. +## Actions and Events - - -```ts -import { CometChat } from "@cometchat/chat-sdk-javascript"; -import { - CometChatGroupMembers, - SelectionMode, -} from "@cometchat/chat-uikit-react"; -import React from "react"; +### Callback Props -const GroupMembersDemo = () => { - const [chatGroup, setChatGroup] = React.useState(); +#### onItemClick - React.useEffect(() => { - CometChat.getGroup("guid").then((group) => { - setChatGroup(group); - }); - }, []); +Fires when a member row is tapped. - function handleOnSelect( - groupMembers: CometChat.GroupMember, - selected: boolean - ): void { - console.log(groupMembers, selected); - /** Your custom onSelect actions */ - } +```tsx +import { CometChatGroupMembers } from "@cometchat/chat-uikit-react"; +import { CometChat } from "@cometchat/chat-sdk-javascript"; +function GroupMembersWithClick({ group }: { group: CometChat.Group }) { return ( - <> - {chatGroup && ( - - )} - + { + console.log("Selected member:", member.getName()); + }} + /> ); -}; - -export default GroupMembersDemo; +} ``` - +#### onSelect - -```js -import { CometChat } from "@cometchat/chat-sdk-javascript"; +Fires when a member is checked/unchecked in multi-select mode. Requires `selectionMode` to be set. + +```tsx +import { useState } from "react"; import { - CometChatGroupMembers, - SelectionMode, + CometChatGroupMembers, + SelectionMode, } from "@cometchat/chat-uikit-react"; -import React, { useEffect, useState } from "react"; +import { CometChat } from "@cometchat/chat-sdk-javascript"; -const GroupMembersDemo = () => { - const [chatGroup, setChatGroup] = useState(null); +function BatchSelectMembers({ group }: { group: CometChat.Group }) { + const [selected, setSelected] = useState>(new Set()); - useEffect(() => { - CometChat.getGroup("guid").then((group) => { - setChatGroup(group); + return ( + { + setSelected((prev) => { + const next = new Set(prev); + const uid = member.getUid(); + isSelected ? next.add(uid) : next.delete(uid); + return next; }); - }, []); - - function handleOnSelect(groupMembers, selected) { - console.log(groupMembers); - /** Your custom onSelect actions - } - - return ( - <> - {chatGroup && ( - - )} - - ); -}; - -export default GroupMembersDemo; + }} + /> + ); +} ``` - - - - -##### 2. onItemClick +#### onEmpty -The `onItemClick` event is activated when you click on the Group Members List item. This action does not come with any predefined behavior. However, you have the flexibility to override this event and tailor it to suit your needs using the following code snippet. +Fires when the member list has no data to display. - - -```ts -import { CometChat } from "@cometchat/chat-sdk-javascript"; +```tsx import { CometChatGroupMembers } from "@cometchat/chat-uikit-react"; -import React from "react"; - -const GroupMembersDemo = () => { - const [chatGroup, setChatGroup] = React.useState(); - - React.useEffect(() => { - CometChat.getGroup("guid").then((group) => { - setChatGroup(group); - }); - }, []); - - function handleOnItemClick(groupMembers: CometChat.GroupMember): void { - console.log(groupMembers, "your custom on item click action"); - } +import { CometChat } from "@cometchat/chat-sdk-javascript"; +function GroupMembersWithEmpty({ group }: { group: CometChat.Group }) { return ( - <> - {chatGroup && ( - - )} - + console.log("No members found")} + /> ); -}; - -export default GroupMembersDemo; +} ``` - - - -```js -import { CometChat } from "@cometchat/chat-sdk-javascript"; -import { CometChatGroupMembers } from "@cometchat/chat-uikit-react"; -import { useEffect, useState } from "react"; - -const GroupMembersDemo = () => { - const [chatGroup, setChatGroup] = useState(null); +#### onError - useEffect(() => { - CometChat.getGroup("guid").then((group) => { - setChatGroup(group); - }); - }, []); +Fires on internal errors (network failure, auth issue, SDK exception). - function handleOnItemClick(groupMembers) { - console.log(groupMembers, "your custom on item click action"); - } +```tsx +import { CometChatGroupMembers } from "@cometchat/chat-uikit-react"; +import { CometChat } from "@cometchat/chat-sdk-javascript"; +function GroupMembersWithError({ group }: { group: CometChat.Group }) { return ( - <> - {chatGroup && ( - - )} - + { + console.error("CometChatGroupMembers error:", error); + }} + /> ); -}; - -export default GroupMembersDemo; +} ``` - +### Global UI Events - +`CometChatGroupEvents` emits events subscribable from anywhere in the application. The component both emits and subscribes to these events. -##### 3. onEmpty +Events emitted by this component: -This action allows you to specify a callback function to be executed when a certain condition, typically the absence of data or content, is met within the component or element. +| Event | Fires when | Payload | +| --- | --- | --- | +| `ccGroupMemberKicked` | A member is kicked | `IGroupMemberKickedBanned` | +| `ccGroupMemberBanned` | A member is banned | `IGroupMemberKickedBanned` | +| `ccGroupMemberScopeChanged` | A member's scope changes | `IGroupMemberScopeChanged` | - - -```ts -import { CometChat } from "@cometchat/chat-sdk-javascript"; -import { CometChatGroupMembers } from "@cometchat/chat-uikit-react"; -import React from "react"; +Events subscribed internally: + +| Event | Internal behavior | +| --- | --- | +| `ccGroupMemberKicked` | Removes the kicked member from the list | +| `ccGroupMemberBanned` | Removes the banned member from the list | +| `ccGroupMemberScopeChanged` | Updates the member's scope in the list | +| `ccGroupMemberAdded` | Appends newly added members to the list | + +```tsx +import { useEffect } from "react"; +import { CometChatGroupEvents } from "@cometchat/chat-uikit-react"; -const GroupMembersDemo = () => { - const [chatGroup, setChatGroup] = React.useState(); +function useGroupMemberEvents() { + useEffect(() => { + const kickedSub = CometChatGroupEvents.ccGroupMemberKicked.subscribe( + (item) => { + console.log("Member kicked:", item.kickedUser.getName()); + } + ); + const scopeSub = CometChatGroupEvents.ccGroupMemberScopeChanged.subscribe( + (item) => { + console.log("Scope changed:", item.updatedUser.getName(), "to", item.scopeChangedTo); + } + ); - React.useEffect(() => { - CometChat.getGroup("guid").then((group) => { - setChatGroup(group); - }); + return () => { + kickedSub?.unsubscribe(); + scopeSub?.unsubscribe(); + }; }, []); +} +``` - function handleOnEmpty(): void { - console.log("your custom on empty actions"); - } +### SDK Events (Real-Time, Automatic) - return ( - <> - {chatGroup && ( - - )} - - ); -}; +The component listens to these SDK events internally. No manual attachment needed unless additional side effects are required. -export default GroupMembersDemo; -``` +| SDK Listener | Internal behavior | +| --- | --- | +| `onGroupMemberScopeChanged` | Updates the member's scope in the list | +| `onGroupMemberKicked` | Removes the kicked member from the list | +| `onGroupMemberBanned` | Removes the banned member from the list | +| `onMemberAddedToGroup` | Appends the new member to the list | +| `onGroupMemberLeft` | Removes the member who left from the list | +| `onGroupMemberJoined` | Appends the joined member to the list | +| `onUserOnline` / `onUserOffline` | Updates the member's online/offline status (disabled when `hideUserStatus={true}`) | - + +In React 18 StrictMode, `useEffect` runs twice on mount in development. The component handles listener cleanup internally, but any additional listeners added alongside the component need cleanup in the `useEffect` return function to avoid duplicate event handling. + - -```js -import { CometChat } from "@cometchat/chat-sdk-javascript"; -import { CometChatGroupMembers } from "@cometchat/chat-uikit-react"; -import { useEffect, useState } from "react"; +--- -const GroupMembersDemo = () => { - const [chatGroup, setChatGroup] = useState(null); +## Custom View Slots - useEffect(() => { - CometChat.getGroup("guid").then((group) => { - setChatGroup(group); - }); - }, []); +Each slot replaces a section of the default UI. Slots that accept a member parameter receive the `CometChat.GroupMember` object for that row. - function handleOnEmpty() { - console.log("your custom on empty actions"); - } +| Slot | Signature | Replaces | +| --- | --- | --- | +| `itemView` | `(groupMember: CometChat.GroupMember) => JSX.Element` | Entire list item row | +| `leadingView` | `(groupMember: CometChat.GroupMember) => JSX.Element` | Avatar / left section | +| `titleView` | `(groupMember: CometChat.GroupMember) => JSX.Element` | Name / title text | +| `subtitleView` | `(groupMember: CometChat.GroupMember) => JSX.Element` | Subtitle text | +| `trailingView` | `(groupMember: CometChat.GroupMember) => JSX.Element` | Right section (scope badge / actions) | +| `headerView` | `JSX.Element` | Entire header bar | +| `loadingView` | `JSX.Element` | Loading spinner | +| `emptyView` | `JSX.Element` | Empty state | +| `errorView` | `JSX.Element` | Error state | +| `options` | `(group: CometChat.Group, groupMember: CometChat.GroupMember) => CometChatOption[]` | Context menu / hover actions | - return ( - <> - {chatGroup && ( - - )} - - ); -}; +### itemView -export default GroupMembersDemo; -``` +Replace the entire list item row. - +Default: - + + + -##### 4. onError +Customized: -This action doesn't change the behavior of the component but rather listens for any errors that occur in the Group Members component. + + + -```ts +```tsx import { CometChat } from "@cometchat/chat-sdk-javascript"; -import { CometChatGroupMembers } from "@cometchat/chat-uikit-react"; -import React from "react"; - -const GroupMembersDemo = () => { - const [chatGroup, setChatGroup] = React.useState(); - - React.useEffect(() => { - CometChat.getGroup("guid").then((group) => { - setChatGroup(group); - }); - }, []); - - function handleOnError(error: CometChat.CometChatException): void { - /** Your Custom on error actions */ - } +import { + CometChatAvatar, + CometChatGroupMembers, +} from "@cometchat/chat-uikit-react"; - return ( - <> - {chatGroup && ( - - )} - - ); -}; +function CustomItemViewMembers({ group }: { group: CometChat.Group }) { + const getItemView = (member: CometChat.GroupMember) => { + const scope = member.getScope(); + return ( +
+
+ +
+
+
{member.getName()}
+
+ {scope} +
+
+
+ ); + }; -export default GroupMembersDemo; + return ; +} ``` -
+ +```css +.group-member-list-item { + display: flex; + min-width: 240px; + padding: 8px 16px; + align-items: center; + gap: 12px; + background: #fff; +} - -```js -import { CometChat } from "@cometchat/chat-sdk-javascript"; -import { CometChatGroupMembers } from "@cometchat/chat-uikit-react"; -import { useEffect, useState } from "react"; +.group-member-list-item__content { + display: flex; + justify-content: space-between; + align-items: center; + width: 100%; +} -const GroupMembersDemo = () => { - const [chatGroup, setChatGroup] = useState(null); +.group-member-list-item__avatar { + width: 40px; + height: 40px; +} - useEffect(() => { - CometChat.getGroup("guid").then((group) => { - setChatGroup(group); - }); - }, []); +.group-member-list-item__content-name { + overflow: hidden; + color: #141414; + text-overflow: ellipsis; + font: 500 16px Roboto; +} - function handleOnError(error) { - /** Your Custom on error actions */ - } +.group-member-list-item__content-tag { + display: flex; + padding: 4px 12px; + border-radius: 1000px; + background: #edeafa; + color: #6852d6; + font: 400 12px Roboto; +} - return ( - <> - {chatGroup && ( - - )} - - ); -}; +.group-member-list-item__content-tag-owner { + background: #6852d6; + color: #fff; +} -export default GroupMembersDemo; -``` +.group-member-list-item__content-tag-admin { + border: 1px solid #6852d6; +} +.group-member-list-item__content-tag-participant { + display: none; +} +``` -
-*** - -### Filters +### subtitleView -**Filters** allow you to customize the data displayed in a list within a Component. You can filter the list based on your specific criteria, allowing for a more customized. Filters can be applied using RequestBuilders of Chat SDK. +Replace the subtitle text. Joined date example. -##### 1. GroupMembersRequestBuilder +Default: -The [GroupMembersRequestBuilder](/sdk/javascript/retrieve-group-members) enables you to filter and customize the group members list based on available parameters in GroupMembersRequestBuilder. This feature allows you to create more specific and targeted queries when fetching groups. The following are the parameters available in [GroupMembersRequestBuilder](/sdk/javascript/retrieve-group-members) - -| Methods | Type | Description | -| -------------------- | -------------- | ------------------------------------------------------------------------------------------------- | -| **setLimit** | number | sets the number of group members that can be fetched in a single request, suitable for pagination | -| **setSearchKeyword** | String | used for fetching group members matching the passed string | -| **setScopes** | Array\ | used for fetching group members based on multiple scopes | + + + -**Example** +Customized: -In the example below, we are applying a filter to the Group Members by setting the limit to two and setting the scope to show only admin and moderator. + + + -```ts +```tsx import { CometChat } from "@cometchat/chat-sdk-javascript"; import { CometChatGroupMembers } from "@cometchat/chat-uikit-react"; -import React from "react"; - -const GroupMembersDemo = () => { - const [chatGroup, setChatGroup] = React.useState(); - React.useEffect(() => { - CometChat.getGroup("guid").then((group) => { - setChatGroup(group); - }); - }, []); - - return ( - <> - {chatGroup && ( - - )} - - ); -}; +function SubtitleMembers({ group }: { group: CometChat.Group }) { + const getSubtitleView = (member: CometChat.GroupMember) => { + const date = new Date(member.getJoinedAt() * 1000).toLocaleDateString(); + return
Joined: {date}
; + }; -export default GroupMembersDemo; + return ; +} ``` -
+ +```css +.group-member-subtitle { + overflow: hidden; + color: #727272; + text-overflow: ellipsis; + white-space: nowrap; + font: 400 14px Roboto; +} +``` + +
- -```js -import { CometChat } from "@cometchat/chat-sdk-javascript"; -import { CometChatGroupMembers } from "@cometchat/chat-uikit-react"; -import { useEffect, useState } from "react"; +### trailingView -const GroupMembersDemo = () => { - const [chatGroup, setChatGroup] = useState(null); +Replace the right section. Scope tag example. - useEffect(() => { - CometChat.getGroup("guid").then((group) => { - setChatGroup(group); - }); - }, []); +Default: - return ( - <> - {chatGroup && ( - - )} - - ); -}; + + + -export default GroupMembersDemo; -``` +Customized: - + + + + + + +```tsx +import { CometChat } from "@cometchat/chat-sdk-javascript"; +import { CometChatGroupMembers } from "@cometchat/chat-uikit-react"; + +function TrailingViewMembers({ group }: { group: CometChat.Group }) { + const getTrailingView = (member: CometChat.GroupMember) => { + return ( +
+ {member.getScope()} +
+ ); + }; + return ; +} +``` +
+ +```css +.group-member-scope-tag { + display: flex; + padding: 4px 12px; + border-radius: 1000px; + background: #edeafa; + color: #6852d6; + font: 400 12px Roboto; +} +``` +
-##### 2. SearchRequestBuilder +### headerView -The SearchRequestBuilder uses [GroupMembersRequestBuilder](/sdk/javascript/retrieve-group-members) enables you to filter and customize the search list based on available parameters in GroupMembersRequestBuilder. This feature allows you to keep uniformity between the displayed Group Members List and searched Group Members List. +Replace the entire header bar. -**Example** + + + -```ts +```tsx +import { + CometChatGroupMembers, + CometChatButton, + getLocalizedString, +} from "@cometchat/chat-uikit-react"; import { CometChat } from "@cometchat/chat-sdk-javascript"; -import { CometChatGroupMembers } from "@cometchat/chat-uikit-react"; -import React from "react"; - -const GroupMembersDemo = () => { - const [chatGroup, setChatGroup] = React.useState(); - - React.useEffect(() => { - CometChat.getGroup("guid").then((group) => { - setChatGroup(group); - }); - }, []); +function CustomHeaderMembers({ group }: { group: CometChat.Group }) { return ( - <> - {chatGroup && ( - - )} - + +
+ {getLocalizedString("GROUP_MEMBERS")} +
+ { /* handle click */ }} /> +
+ } + /> ); -}; - -export default GroupMembersDemo; +} ``` +
+ +```css +.group-members__header { + display: flex; + width: 100%; + padding: 8px 16px; + align-items: center; + justify-content: space-between; + gap: 12px; + border-radius: 10px; + border: 1px solid #e8e8e8; + background: #edeafa; +} +.group-members__header__title { + overflow: hidden; + color: #141414; + text-overflow: ellipsis; + font: 700 24px Roboto; +} +``` +
- -```js -import { CometChat } from "@cometchat/chat-sdk-javascript"; -import { CometChatGroupMembers } from "@cometchat/chat-uikit-react"; -import { useEffect, useState } from "react"; +### options -const GroupMembersDemo = () => { - const [chatGroup, setChatGroup] = useState(null); +Replace the context menu / hover actions on each member item. The `options` callback receives both the group and the member. - useEffect(() => { - CometChat.getGroup("guid").then((group) => { - setChatGroup(group); - }); - }, []); + + + + + +```tsx +import { CometChat } from "@cometchat/chat-sdk-javascript"; +import { + CometChatGroupMembers, + CometChatOption, +} from "@cometchat/chat-uikit-react"; + +function CustomOptionsMembers({ group }: { group: CometChat.Group }) { return ( - <> - {chatGroup && ( - - )} - + [ + new CometChatOption({ + id: "kick", + title: "Kick User", + onClick: () => { /* kick logic */ }, + }), + ]} + /> ); -}; - -export default GroupMembersDemo; +} ``` - + +```css +.cometchat-group-members .cometchat-menu-list__main-menu-item-icon { + background: #f44649; +} +.cometchat-group-members .cometchat-menu-list__menu { + background: transparent; + box-shadow: none; +} +``` + -*** - -### Events - -[Events](/ui-kit/react/components-overview#events) are emitted by a `Component`. By using event you can extend existing functionality. Being global events, they can be applied in Multiple Locations and are capable of being Added or Removed. +--- -Events emitted by the Group Members component is as follows. +## Common Patterns -| Event | Description | -| ----------------------------- | ----------------------------------------------------------------- | -| **ccGroupMemberBanned** | Triggers when the group member banned from the group successfully | -| **ccGroupMemberKicked** | Triggers when the group member kicked from the group successfully | -| **ccGroupMemberScopeChanged** | Triggers when the group member scope is changed in the group | +### Hide member management actions - - ```tsx -const ccGroupMemberBanned = CometChatGroupEvents.ccGroupMemberBanned.subscribe( - (item: IGroupMemberKickedBanned) => { - /** Your Code */ - } -); - -const ccGroupMemberKicked = CometChatGroupEvents.ccGroupMemberKicked.subscribe( - (item: IGroupMemberKickedBanned) => { - /** Your Code */ - } -); +import { CometChatGroupMembers } from "@cometchat/chat-uikit-react"; +import { CometChat } from "@cometchat/chat-sdk-javascript"; -const ccGroupMemberScopeChanged = - CometChatGroupEvents.ccGroupMemberScopeChanged.subscribe( - (item: IGroupMemberScopeChanged) => { - /** Your Code */ - } +function ReadOnlyMembers({ group }: { group: CometChat.Group }) { + return ( + ); +} ``` - +### Admins and moderators only - +```tsx +import { CometChatGroupMembers } from "@cometchat/chat-uikit-react"; +import { CometChat } from "@cometchat/chat-sdk-javascript"; + +function AdminMembers({ group }: { group: CometChat.Group }) { + return ( + + ); +} +``` -*** +### Minimal chrome - - ```tsx -ccGroupMemberBanned?.unsubscribe(); - -ccGroupMemberKicked?.unsubscribe(); +import { CometChatGroupMembers } from "@cometchat/chat-uikit-react"; +import { CometChat } from "@cometchat/chat-sdk-javascript"; -ccGroupMemberScopeChanged?.unsubscribe(); +function MinimalMembers({ group }: { group: CometChat.Group }) { + return ( + + ); +} ``` - +--- - +## CSS Architecture -*** +The component uses CSS custom properties (design tokens) defined in `@cometchat/chat-uikit-react/css-variables.css`. The cascade: -## Customization +1. Global tokens (e.g., `--cometchat-primary-color`, `--cometchat-background-color-01`) are set on the `.cometchat` root wrapper. +2. Component CSS (`.cometchat-group-members`) consumes these tokens via `var()` with fallback values. +3. Overrides target `.cometchat-group-members` descendant selectors in a global stylesheet. -To fit your app's design requirements, you can customize the appearance of the Group Members component. +### Key Selectors -### Style +| Target | Selector | +| --- | --- | +| Root | `.cometchat-group-members` | +| Header title | `.cometchat-group-members .cometchat-list__header-title` | +| List item | `.cometchat-group-members .cometchat-list-item` | +| Body title | `.cometchat-group-members .cometchat-list-item__body-title` | +| Trailing view | `.cometchat-group-members .cometchat-list-item__trailing-view` | +| Scope badge | `.cometchat-group-members__trailing-view-options` | +| Admin scope badge | `.cometchat-group-members__trailing-view-options-admin` | +| Owner scope badge | `.cometchat-group-members__trailing-view-options-owner` | +| Participant scope badge | `.cometchat-group-members__trailing-view-options-participant` | +| Online status | `.cometchat-group-members__list-item-online .cometchat-list-item__status` | +| Scope change dropdown | `.cometchat-group-members .cometchat-menu-list__sub-menu` | +| Empty state | `.cometchat-group-members__empty-state-view` | +| Error state | `.cometchat-group-members__error-state-view` | +| Shimmer loading | `.cometchat-group-members__shimmer` | +| Backdrop (modal) | `.cometchat-group-members__backdrop` | -Using CSS you can customize the look and feel of the component in your app like the color, size, shape, and fonts. +### Example: Brand-themed group members - - -```ts -import { CometChat } from "@cometchat/chat-sdk-javascript"; -import { CometChatGroupMembers } from "@cometchat/chat-uikit-react"; -import React from "react"; -import "./GroupMembersStyle.css"; - -const GroupMembersDemo = () => { - const [chatGroup, setChatGroup] = React.useState(); - - React.useEffect(() => { - CometChat.getGroup("guid").then((group) => { - setChatGroup(group); - }); - }, []); - - return <>{chatGroup && }; -}; - -export default GroupMembersDemo; -``` - - - - ```css .cometchat-group-members .cometchat-list__header-title { background: #feede1; @@ -660,804 +816,382 @@ export default GroupMembersDemo; font-family: "Times New Roman"; } -.cometchat-group-members .cometchat-list-item__body-title, -.cometchat-group-members .cometchat-search-bar__input::placeholder { +.cometchat-group-members .cometchat-list-item__body-title { font-family: "Times New Roman"; } .cometchat-group-members .cometchat-group-members__trailing-view-options { - background: #feede1; - color: #f76808; - font-family: "Times New Roman"; -} - -.cometchat-group-members .cometchat-group-members__trailing-view-options-admin { - border: 1px solid #f76808; -} - -.cometchat-group-members .cometchat-group-members__trailing-view-options-owner { - background: #f76808; - color: #fff; font-family: "Times New Roman"; } - -.cometchat-group-members .cometchat-list-item__leading-view, -.cometchat-group-members .cometchat-avatar { - height: 40px; - width: 40px; -} ``` - - - - -*** - -### Functionality - -These are a set of small functional customizations that allow you to fine-tune the overall experience of the component. With these, you can change text, set custom icons, and toggle the visibility of UI elements. - - - -```ts -import { CometChat } from "@cometchat/chat-sdk-javascript"; -import { CometChatGroupMembers } from "@cometchat/chat-uikit-react"; -import React from "react"; +### Customization Matrix -const GroupMembersDemo = () => { - const [chatGroup, setChatGroup] = React.useState(); +| What to change | Where | Property/API | Example | +| --- | --- | --- | --- | +| Override behavior on user interaction | Component props | `on` callbacks | `onItemClick={(m) => openProfile(m)}` | +| Filter which members appear | Component props | `groupMemberRequestBuilder` | `groupMemberRequestBuilder={new CometChat.GroupMembersRequestBuilder("GUID").setScopes(["admin"])}` | +| Toggle visibility of UI elements | Component props | `hide` boolean props | `hideKickMemberOption={true}` | +| Replace a section of the list item | Component props | `View` render props | `subtitleView={(m) =>
{m.getScope()}
}` | +| Change colors, fonts, spacing | Global CSS | Target `.cometchat-group-members` class | `.cometchat-group-members .cometchat-avatar { border-radius: 8px; }` | - React.useEffect(() => { - CometChat.getGroup("guid").then((group) => { - setChatGroup(group); - }); - }, []); +--- - return ( - <> - {chatGroup && ( - - )} - - ); -}; +## Accessibility -export default GroupMembersDemo; -``` +The component renders a scrollable list of interactive items. Each member row is keyboard-focusable and activates on Enter/Space. The scope change dropdown and context menu (options) are accessible via keyboard. Online status indicators use CSS — add `aria-label` attributes via `itemView` if screen reader descriptions are needed. -
+--- - -```js -import { CometChat } from "@cometchat/chat-sdk-javascript"; -import { CometChatGroupMembers } from "@cometchat/chat-uikit-react"; -import { useEffect, useState } from "react"; +--- -const GroupMembersDemo = () => { - const [chatGroup, setChatGroup] = useState(null); +## Props - useEffect(() => { - CometChat.getGroup("guid").then((group) => { - setChatGroup(group); - }); - }, []); +All props are optional unless noted otherwise. - return ( - <> - {chatGroup && ( - - )} - - ); -}; +--- -export default GroupMembersDemo; -``` +### disableLoadingState - +Skips the loading spinner when re-fetching. -
+| | | +| --- | --- | +| Type | `boolean` | +| Default | `false` | -Below is a list of customizations along with corresponding code snippets, +--- -| Property | Description | Code | -| ---------------------------- | ------------------------------------------------------------------------- | ---------------------------------------- | -| **Hide Search** | Hides the default search bar. | `hideSearch={true}` | -| **Hide Error** | Hides the default and custom error view passed in `errorView` prop. | `hideError={true}` | -| **Hide Kick Member Option** | Hides the option to kick a member from the group. | `hideKickMemberOption={true}` | -| **Hide Ban Member Option** | Hides the option to ban a member from the group. | `hideBanMemberOption={true}` | -| **Hide Scope Change Option** | Hides the option to change the scope of a group member. | `hideScopeChangeOption={true}` | -| **Hide User Status** | Hides the user's online/offline status indicator. | `hideUserStatus={true}` | -| **Group** | The group for which members are being fetched. | `group={chatGroup}` | -| **Search Keyword** | The keyword used to filter the group members list. | `searchKeyword="admin"` | -| **Selection Mode** | Selection mode to use for the default list item view. | `selectionMode={SelectionMode.multiple}` | -| **Show Scrollbar** | Controls the visibility of the scrollbar in the list. | `showScrollbar={true}` | -| **Loading View** | A custom view to display during the loading state. | `loadingView={}` | -| **Error View** | Custom view for the error state of the component. | `errorView={}` | -| **Empty View** | A custom view to display when no group members are available in the list. | | +### emptyView -*** +Custom component displayed when there are no members. -### Advanced +| | | +| --- | --- | +| Type | `JSX.Element` | +| Default | Built-in empty state | -For advanced-level customization, you can set custom views to the component. This lets you tailor each aspect of the component to fit your exact needs and application aesthetics. You can create and define your views, layouts, and UI elements and then incorporate those into the component. +--- -*** +### errorView -#### ItemView +Custom component displayed when an error occurs. -With this property, you can assign a custom ListItem to the Group Members Component. +| | | +| --- | --- | +| Type | `JSX.Element` | +| Default | Built-in error state | -Shown below is the default chat interface. +Hidden when `hideError={true}`. - - - +--- -The customized chat interface is displayed below. +### group - - - +The group whose members are fetched and displayed. **Required.** -Use the following code to achieve the customization shown above. +| | | +| --- | --- | +| Type | `CometChat.Group` | +| Default | — | - - -```ts -import { CometChat, GroupMember } from "@cometchat/chat-sdk-javascript"; -import React from "react"; -import { - CometChatAvatar, - CometChatGroupMembers, - CometChatOption, - CometChatUIKitLoginListener, - GroupMemberUtils, - localize, -} from "@cometchat/chat-uikit-react"; -import "./GroupMembersStyle.css"; +--- -const GroupMembersDemo = () => { - const [chatGroup, setChatGroup] = React.useState(); +### groupMemberRequestBuilder - React.useEffect(() => { - CometChat.getGroup("guid").then((group) => { - setChatGroup(group); - }); - }, []); +Controls which members load and in what order. - const getCustomItemView = (groupMember: GroupMember) => { - const loggedInUser = CometChatUIKitLoginListener.getLoggedInUser(); - let scope: string | CometChatOption[] = - GroupMemberUtils.getViewMemberOptions( - groupMember, - chatGroup!, - loggedInUser?.getUid() - ); - if (typeof scope !== "string") { - scope = groupMember.getScope(); - } +| | | +| --- | --- | +| Type | `CometChat.GroupMembersRequestBuilder` | +| Default | SDK default (30 per page) | - return ( -
-
- - {groupMember.getStatus() === "online" && ( -
- )} -
-
-
- {groupMember.getName()} -
-
- {localize(scope.toUpperCase())} -
-
-
- ); - }; +Pass the builder instance, not the result of `.build()`. - return ( - <> - {chatGroup && ( - - )} - - ); -}; +--- -export default GroupMembersDemo; -``` +### headerView - +Custom component rendered as the entire header bar. - -```css -.group-member-list-item { - display: flex; - min-width: 240px; - max-width: 1440px; - padding: 8px 16px; - align-items: center; - gap: 12px; - flex: 1 0 0; - border-right: 1px solid #f5f5f5; - background: #fff; -} +| | | +| --- | --- | +| Type | `JSX.Element` | +| Default | Built-in header with title | -.group-member-list-item__content { - display: flex; - justify-content: space-between; - align-items: center; - align-self: stretch; - width: 100%; -} +--- -.group-member-list-item__avatar { - display: flex; - width: 40px; - height: 40px; -} +### hideBanMemberOption -.group-member-list-item__avatar .cometchat-avatar, -.group-member-list-item__avatar .cometchat-avatar__image { - height: 40px; - width: 40px; - border-radius: 12px; -} +Hides the option to ban a member from the group. -.group-member-list-item__avatar-status { - width: 10px; - padding: 5px; - height: 10px; - border-radius: 1000px; - border: 1px solid #fff; - position: relative; - background: #09c26f; - left: -12px; - top: 30px; -} +| | | +| --- | --- | +| Type | `boolean` | +| Default | `false` | -.group-member-list-item__content-name { - overflow: hidden; - color: #141414; - text-overflow: ellipsis; - font: 500 16px Roboto; -} +--- -.group-member-list-item__content-tag { - display: flex; - padding: 4px 12px; - justify-content: center; - align-items: center; - gap: 20px; - border-radius: 1000px; - background: #edeafa; - overflow: hidden; - color: #6852d6; - text-overflow: ellipsis; - font: 400 12px Roboto; -} +### hideError -.group-member-list-item__content-tag-owner { - background: #6852d6; - color: #fff; -} +Hides the default and custom error views. -.group-member-list-item__content-tag-admin { - border: 1px solid #6852d6; -} +| | | +| --- | --- | +| Type | `boolean` | +| Default | `false` | -.group-member-list-item__content-tag-participant { - display: none; -} -``` +--- - +### hideKickMemberOption - +Hides the option to kick a member from the group. -*** +| | | +| --- | --- | +| Type | `boolean` | +| Default | `false` | -#### TitleView +--- -The customized chat interface is displayed below. +### hideScopeChangeOption - - - +Hides the option to change the scope of a group member. -Use the following code to achieve the customization shown above. +| | | +| --- | --- | +| Type | `boolean` | +| Default | `false` | - - -```ts -import React from "react"; -import { CometChat } from "@cometchat/chat-sdk-javascript"; -import { CometChatGroups } from "@cometchat/chat-uikit-react"; - -// Custom title view component -const customTitleView = (member: CometChat.GroupMember) => { - return
- {member.getName()} - {member.getRole()} -
; -} +--- -; -``` +### hideSearch -
+Hides the default search bar. - -```css -.group-members__title-view{ - display: flex; - align-items: center; - gap: 4px; - align-self: stretch; - } - .group-members__title-view-name{ - overflow: hidden; - color: #141414; - text-overflow: ellipsis; - font:500 16px Roboto - } - .group-members__title-view-type{ - color: #FFF; - font: 600 8px Roboto; - display: flex; - height: 15px; - padding: 1px 3px; - justify-content: center; - align-items: center; - gap: 3px; - border-radius: 7px; - background: #09C26F; - } - .group-members__title-view-public .group-members__title-view-role{ - //add css based on roles - background: #0B7BEA; - } -``` +| | | +| --- | --- | +| Type | `boolean` | +| Default | `false` | - +--- -
+### hideUserStatus -*** +Hides the user's online/offline status indicator. -#### SubtitleView +| | | +| --- | --- | +| Type | `boolean` | +| Default | `false` | -You can customize the subtitle view for each group members to meet your requirements. +--- -Shown below is the default chat interface. +### itemView - - - +Custom renderer for the entire list item row. -The customized chat interface is displayed below. +| | | +| --- | --- | +| Type | `(groupMember: CometChat.GroupMember) => JSX.Element` | +| Default | Built-in list item | - - - +--- -Use the following code to achieve the customization shown above. +### leadingView - - -```ts -import { CometChat, GroupMember } from "@cometchat/chat-sdk-javascript"; -import React from "react"; -import { CometChatGroupMembers } from "@cometchat/chat-uikit-react"; -import "./GroupMembersStyle.css"; +Custom renderer for the avatar / left section. -const GroupMembersDemo = () => { - const [chatGroup, setChatGroup] = React.useState(); +| | | +| --- | --- | +| Type | `(groupMember: CometChat.GroupMember) => JSX.Element` | +| Default | Built-in avatar | - React.useEffect(() => { - CometChat.getGroup("guid").then((group) => { - setChatGroup(group); - }); - }, []); +--- - const getCustomSubtitleView = (groupMember: GroupMember) => { - const formatTime = (timestamp: number) => { - const date = new Date(timestamp * 1000); - return date.toLocaleDateString(); - }; - return ( -
- {"Joined at: " + formatTime(groupMember.getJoinedAt())} -
- ); - }; +### loadingView - return ( - <> - {chatGroup && ( - - )} - - ); -}; +Custom component displayed during the loading state. -export default GroupMembersDemo; -``` +| | | +| --- | --- | +| Type | `JSX.Element` | +| Default | Built-in shimmer | -
+--- - -```css -.group-member-subtitle { - overflow: hidden; - color: #727272; - text-overflow: ellipsis; - white-space: nowrap; - font: 400 14px Roboto; -} -``` +### onEmpty - +Callback fired when the member list is empty. -
+| | | +| --- | --- | +| Type | `() => void` | +| Default | `undefined` | -*** +--- -#### LeadingView +### onError -The customized chat interface is displayed below. +Callback fired when the component encounters an error. - - - +| | | +| --- | --- | +| Type | `((error: CometChat.CometChatException) => void) \| null` | +| Default | `undefined` | -Use the following code to achieve the customization shown above. +--- - - -```ts -import React from "react"; -import { CometChat } from "@cometchat/chat-sdk-javascript"; -import { CometChatGroupMembers,CometChatAvatar } from "@cometchat/chat-uikit-react"; +### onItemClick -// Custom leading view component -const customLeadingView = (member: CometChat.GroupMember): JSX.Element => { - // Determine the member's scope or owner status - const scope = member.getUid() === group.getOwner() ? "owner" : member.getScope(); +Callback fired when a member row is clicked. - return ( -
- - - {scope} -
- ); -}; -; -``` +| | | +| --- | --- | +| Type | `(groupMember: CometChat.GroupMember) => void` | +| Default | `undefined` | -
+--- - -```css -.cometchat-group-members .cometchat-list-item .group-member__leading-view .cometchat-avatar__image, .cometchat-group-members .cometchat-list-item .group-member__leading-view .cometchat-avatar{ -border-radius: 8px; -height: 48px ; -width: 48px ; -} -.group-member__leading-view-scope{ -display: flex; -width: 48px; -height: 15px; -padding: 1px 3px; -justify-content: center; -align-items: center; -color:#FFF; -font:600 8px/9.6px Roboto; -background:#FFAB00; -position:absolute; -bottom:-2px; -} -.group-member__leading-view{ -position: relative; -} +### onSelect -.group-member__leading-view-participant .group-member__leading-view-scope{ -display: none; -} -.group-member__leading-view-owner .group-member__leading-view-scope{ -background: #0B7BEA; -} -.group-member__leading-view-admin .group-member__leading-view-scope{ -background: #FFAB00; -} -.group-member__leading-view-moderator .group-member__leading-view-scope{ -background: #09C26F; -} -``` +Callback fired when a member is selected/deselected. Requires `selectionMode` to be set. - +| | | +| --- | --- | +| Type | `(groupMember: CometChat.GroupMember, selected: boolean) => void` | +| Default | `undefined` | -
+--- -*** +### options -#### TrailingView +Custom context menu / hover actions for each member item. -You can customize the trailing view for each group members to meet your requirements. +| | | +| --- | --- | +| Type | `(group: CometChat.Group, groupMember: CometChat.GroupMember) => CometChatOption[]` | +| Default | `undefined` | -Shown below is the default chat interface. +--- - - - +### searchKeyword -The customized chat interface is displayed below. +Pre-fills the search and filters the member list. - - - +| | | +| --- | --- | +| Type | `string` | +| Default | `""` | -Use the following code to achieve the customization shown above. +--- - - -```ts -import { CometChat, GroupMember } from "@cometchat/chat-sdk-javascript"; -import React from "react"; -import { - CometChatGroupMembers, - CometChatOption, - CometChatUIKitLoginListener, - GroupMemberUtils, - localize, -} from "@cometchat/chat-uikit-react"; -import "./GroupMembersStyle.css"; +### searchRequestBuilder -const GroupMembersDemo = () => { - const [chatGroup, setChatGroup] = React.useState(); +Controls filtering when the search bar is active. - React.useEffect(() => { - CometChat.getGroup("guid").then((group) => { - setChatGroup(group); - }); - }, []); +| | | +| --- | --- | +| Type | `CometChat.GroupMembersRequestBuilder` | +| Default | `undefined` | - const getCustomTrailingView = (groupMember: GroupMember) => { - const loggedInUser = CometChatUIKitLoginListener.getLoggedInUser(); - let scope: string | CometChatOption[] = - GroupMemberUtils.getViewMemberOptions( - groupMember, - chatGroup!, - loggedInUser?.getUid() - ); - if (typeof scope !== "string") { - scope = groupMember.getScope(); - } - return ( -
- {localize((scope as string).toUpperCase())} -
- ); - }; +--- - return ( - <> - {chatGroup && ( - - )} - - ); -}; +### selectionMode -export default GroupMembersDemo; -``` +Enables single or multi-select checkboxes on list items. -
+| | | +| --- | --- | +| Type | `SelectionMode` | +| Default | `SelectionMode.none` | - -```css -.group-member-scope-tag { - display: flex; - padding: 4px 12px; - justify-content: center; - align-items: center; - gap: 20px; - border-radius: 1000px; - background: #edeafa; - overflow: hidden; - color: #6852d6; - text-overflow: ellipsis; - font: 400 12px Roboto; +```ts +enum SelectionMode { + single, // 0 + multiple, // 1 + none, // 2 } ``` - - -
- -*** - -#### HeaderView - -You can set the Custom headerView to add more options to the Group Members component. - -The customized chat interface is displayed below. - - - - - -Use the following code to achieve the customization shown above. - - - -```ts -import { CometChat } from "@cometchat/chat-sdk-javascript"; -import { CometChatGroupMembers,localize } from "@cometchat/chat-uikit-react"; -import React from "react"; - -const getHeaderView = () => { - return ( -
-
- {localize("GROUP_MEMBERS")} -
- { - // logic here - }} - iconURL={ICON_URL} - /> -
- ); -}; - - -``` +--- -
+### showScrollbar - -```css -.cometchat-group-members__header { - display: flex; - width: 100%; - padding: 8px 16px; - align-items: center; - justify-content: space-between; - gap: 12px; - flex: 1 0 0; - align-self: stretch; - border-radius: 10px; - border: 1px solid #E8E8E8; - background: #EDEAFA; -} -.cometchat-group-members__header__title { - overflow: hidden; - color: #141414; - text-overflow: ellipsis; - font: 700 24px Roboto; -} -.cometchat-group-members__header .cometchat-button .cometchat-button__icon { - background: #6852D6; -} -.cometchat-group-members__header .cometchat-button{ - width: 24px; - border: none; - background: transparent; - border-radius: 0; - display: block; -} -``` +Shows the scrollbar in the member list. - +| | | +| --- | --- | +| Type | `boolean` | +| Default | `false` | -
+--- -*** +### subtitleView -#### Options +Custom renderer for the subtitle text. -You can set the Custom options to the Group Members component. +| | | +| --- | --- | +| Type | `(groupMember: CometChat.GroupMember) => JSX.Element` | +| Default | Built-in subtitle | -The customized chat interface is displayed below. +--- - - - +### titleView -Use the following code to achieve the customization shown above. +Custom renderer for the name / title text. - - -```ts -import { CometChat } from "@cometchat/chat-sdk-javascript"; -import { - CometChatGroupMembers, - CometChatOption, -} from "@cometchat/chat-uikit-react"; -import React from "react"; -import "./GroupMembersStyle.css"; +| | | +| --- | --- | +| Type | `(groupMember: CometChat.GroupMember) => JSX.Element` | +| Default | Built-in title | -const GroupMembersDemo = () => { - const [chatGroup, setChatGroup] = React.useState(); +--- - React.useEffect(() => { - CometChat.getGroup("guid").then((group) => { - setChatGroup(group); - }); - }, []); +### trailingView - return ( - <> - {chatGroup && ( - { - const customOptions = [ - new CometChatOption({ - id: "1", - title: "Kick User", - onClick: () => { - /** Your logic for handling click of custom option. */ - }, - }), - ]; - return customOptions; - }} - /> - )} - - ); -}; +Custom renderer for the right section (scope badge / actions). -export default GroupMembersDemo; -``` +| | | +| --- | --- | +| Type | `(groupMember: CometChat.GroupMember) => JSX.Element` | +| Default | Built-in trailing view | - +--- - -```css -.cometchat-group-members .cometchat-menu-list__main-menu-item-icon { - height: 24px; - width: 24px; - -webkit-mask: url("./assets/delete.svg") center center no-repeat; - background: #f44649; -} +## Events -.cometchat-group-members .cometchat-menu-list__menu, -.cometchat-group-members .cometchat-menu-list__main-menu-item { - background: transparent; - box-shadow: none; -} -``` +| Event | Payload | Fires when | +| --- | --- | --- | +| `CometChatGroupEvents.ccGroupMemberKicked` | `IGroupMemberKickedBanned` | Member kicked | +| `CometChatGroupEvents.ccGroupMemberBanned` | `IGroupMemberKickedBanned` | Member banned | +| `CometChatGroupEvents.ccGroupMemberScopeChanged` | `IGroupMemberScopeChanged` | Member scope changed | +| `CometChatGroupEvents.ccGroupMemberAdded` | `IGroupMemberAdded` | Members added | - +All events are RxJS `Subject` instances. Subscribe with `.subscribe()`, unsubscribe with the returned subscription's `.unsubscribe()`. - +--- -*** +## CSS Selectors + +| Target | Selector | +| --- | --- | +| Root | `.cometchat-group-members` | +| Header title | `.cometchat-group-members .cometchat-list__header-title` | +| List item | `.cometchat-group-members .cometchat-list-item` | +| Body title | `.cometchat-group-members .cometchat-list-item__body-title` | +| Trailing view | `.cometchat-group-members .cometchat-list-item__trailing-view` | +| Scope badge | `.cometchat-group-members__trailing-view-options` | +| Admin scope badge | `.cometchat-group-members__trailing-view-options-admin` | +| Owner scope badge | `.cometchat-group-members__trailing-view-options-owner` | +| Participant scope badge | `.cometchat-group-members__trailing-view-options-participant` | +| Online status | `.cometchat-group-members__list-item-online .cometchat-list-item__status` | +| Scope change dropdown | `.cometchat-group-members .cometchat-menu-list__sub-menu` | +| Scope change list | `.cometchat-group-members .cometchat-menu-list__sub-menu-list` | +| Empty state | `.cometchat-group-members__empty-state-view` | +| Empty state title | `.cometchat-group-members__empty-state-view-body-title` | +| Error state | `.cometchat-group-members__error-state-view` | +| Error state title | `.cometchat-group-members__error-state-view-body-title` | +| Shimmer loading | `.cometchat-group-members__shimmer` | +| Backdrop | `.cometchat-group-members__backdrop` | diff --git a/ui-kit/react/groups.mdx b/ui-kit/react/groups.mdx index 27bd1cd69..3e15c061f 100644 --- a/ui-kit/react/groups.mdx +++ b/ui-kit/react/groups.mdx @@ -1,794 +1,622 @@ --- title: "Groups" +description: "Searchable, scrollable list of all available groups with icon, name, member count, and group type indicator." --- + +```json +{ + "component": "CometChatGroups", + "package": "@cometchat/chat-uikit-react", + "import": "import { CometChatGroups } from \"@cometchat/chat-uikit-react\";", + "cssImport": "import \"@cometchat/chat-uikit-react/css-variables.css\";", + "description": "Searchable, scrollable list of all available groups with icon, name, member count, and group type indicator.", + "cssRootClass": ".cometchat-groups", + "primaryOutput": { + "prop": "onItemClick", + "type": "(group: CometChat.Group) => void" + }, + "props": { + "data": { + "groupsRequestBuilder": { + "type": "CometChat.GroupsRequestBuilder", + "default": "SDK default (30 per page)", + "note": "Pass the builder, not the result of .build()" + }, + "searchRequestBuilder": { + "type": "CometChat.GroupsRequestBuilder", + "default": "undefined" + }, + "activeGroup": { + "type": "CometChat.Group", + "default": "undefined" + } + }, + "callbacks": { + "onItemClick": "(group: CometChat.Group) => void", + "onSelect": "(group: CometChat.Group, selected: boolean) => void", + "onError": "((error: CometChat.CometChatException) => void) | null" + }, + "visibility": { + "hideSearch": { "type": "boolean", "default": false }, + "hideError": { "type": "boolean", "default": false }, + "hideGroupType": { "type": "boolean", "default": false }, + "showScrollbar": { "type": "boolean", "default": false } + }, + "selection": { + "selectionMode": { + "type": "SelectionMode", + "values": ["SelectionMode.single (0)", "SelectionMode.multiple (1)", "SelectionMode.none (2)"], + "default": "SelectionMode.none" + } + }, + "viewSlots": { + "itemView": "(group: CometChat.Group) => JSX.Element", + "leadingView": "(group: CometChat.Group) => JSX.Element", + "titleView": "(group: CometChat.Group) => JSX.Element", + "subtitleView": "(group: CometChat.Group) => JSX.Element", + "trailingView": "(group: CometChat.Group) => JSX.Element", + "headerView": "JSX.Element", + "loadingView": "JSX.Element", + "emptyView": "JSX.Element", + "errorView": "JSX.Element", + "options": "(group: CometChat.Group) => CometChatOption[]" + } + }, + "events": [ + { + "name": "CometChatGroupEvents.ccGroupCreated", + "payload": "CometChat.Group", + "description": "New group created" + }, + { + "name": "CometChatGroupEvents.ccGroupDeleted", + "payload": "CometChat.Group", + "description": "Group deleted" + }, + { + "name": "CometChatGroupEvents.ccGroupMemberJoined", + "payload": "IGroupMemberJoined", + "description": "User joins a group" + }, + { + "name": "CometChatGroupEvents.ccGroupLeft", + "payload": "IGroupLeft", + "description": "User leaves a group" + }, + { + "name": "CometChatGroupEvents.ccGroupMemberAdded", + "payload": "IGroupMemberAdded", + "description": "Members added to a group" + }, + { + "name": "CometChatGroupEvents.ccGroupMemberScopeChanged", + "payload": "IGroupMemberScopeChanged", + "description": "Member scope changed" + }, + { + "name": "CometChatGroupEvents.ccGroupMemberKicked", + "payload": "IGroupMemberKickedBanned", + "description": "Member kicked" + }, + { + "name": "CometChatGroupEvents.ccGroupMemberBanned", + "payload": "IGroupMemberKickedBanned", + "description": "Member banned" + }, + { + "name": "CometChatGroupEvents.ccOwnershipChanged", + "payload": "IOwnershipChanged", + "description": "Ownership transferred" + } + ], + "sdkListeners": [ + "onGroupMemberJoined", + "onGroupMemberLeft", + "onMemberAddedToGroup", + "onGroupMemberKicked", + "onGroupMemberBanned", + "onGroupMemberScopeChanged" + ], + "compositionExample": { + "description": "Group directory wired to message view", + "components": [ + "CometChatGroups", + "CometChatMessageHeader", + "CometChatMessageList", + "CometChatMessageComposer" + ], + "flow": "onItemClick emits CometChat.Group -> pass to MessageHeader, MessageList, MessageComposer" + }, + "types": { + "CometChatOption": { + "id": "string | undefined", + "title": "string | undefined", + "iconURL": "string | undefined", + "onClick": "(() => void) | undefined" + }, + "SelectionMode": { + "single": 0, + "multiple": 1, + "none": 2 + } + } +} +``` + -## Overview - -The Groups is a Component, showcasing an accessible list of all available groups. It provides an integral search functionality, allowing you to locate any specific groups swiftly and easily. For each group listed, the group name is displayed by default, in conjunction with the group icon when available. Additionally, it provides a useful feature by displaying the number of members in each group as a subtitle, offering valuable context about group size and activity level. +## Where It Fits - - - +`CometChatGroups` is a directory list component. It renders available groups and emits the selected `CometChat.Group` via `onItemClick`. Wire it to `CometChatMessageHeader`, `CometChatMessageList`, and `CometChatMessageComposer` to build a group chat layout. -The Groups component is composed of the following BaseComponents: +```tsx +import { useState } from "react"; +import { + CometChatGroups, + CometChatMessageHeader, + CometChatMessageList, + CometChatMessageComposer, +} from "@cometchat/chat-uikit-react"; +import { CometChat } from "@cometchat/chat-sdk-javascript"; +import "@cometchat/chat-uikit-react/css-variables.css"; -| Components | Description | -| ----------------- | ------------------------------------------------------------------------------------------------------------------------- | -| CometChatList | A reusable container component having title, search box, customisable background and a list view. | -| CometChatListItem | A component that renders data obtained from a Group object on a Tile having a title, subtitle, leading and trailing view. | +function GroupChatApp() { + const [selectedGroup, setSelectedGroup] = useState(); -*** + return ( +
+
+ setSelectedGroup(group)} + /> +
+ {selectedGroup ? ( +
+ + + +
+ ) : ( +
+ Select a group +
+ )} +
+ ); +} +``` -## Usage + + + -### Integration +--- -The following code snippet illustrates how you can directly incorporate the Groups component into your Application. +## Minimal Render - - ```tsx import { CometChatGroups } from "@cometchat/chat-uikit-react"; -import React from "react"; - -const GroupsDemo = () => { - return ; -}; - -export default GroupsDemo; -``` +import "@cometchat/chat-uikit-react/css-variables.css"; - - - -```tsx -import { GroupsDemo } from "./GroupsDemo"; - -export default function App() { +function GroupsDemo() { return ( -
- +
+
); } -``` - - - - - -*** -### Actions +export default GroupsDemo; +``` -[Actions](/ui-kit/react/components-overview#actions) dictate how a component functions. They are divided into two types: Predefined and User-defined. You can override either type, allowing you to tailor the behavior of the component to fit your specific needs. +Root CSS class: `.cometchat-groups` -##### 1. onSelect +--- -The `onSelect` action is activated when you select the done icon while in selection mode. This returns the `group` object along with the boolean flag `selected` to indicate if the group was selected or unselected. +## Filtering Groups -This action does not come with any predefined behavior. However, you have the flexibility to override this event and tailor it to suit your needs using the following code snippet. +Pass a `CometChat.GroupsRequestBuilder` to `groupsRequestBuilder`. Pass the builder instance — not the result of `.build()`. - - -```ts +```tsx +import { CometChatGroups } from "@cometchat/chat-uikit-react"; import { CometChat } from "@cometchat/chat-sdk-javascript"; -import { CometChatGroups, SelectionMode } from "@cometchat/chat-uikit-react"; -import React from "react"; -const GroupsDemo = () => { - function handleOnSelect(group: CometChat.Group, selected: boolean): void { - console.log(group); - //your custom onSelect actions - } +function FilteredGroups() { return ( ); -}; - -export default GroupsDemo; +} ``` - +### Filter Recipes - -```js -import { CometChatGroups, SelectionMode } from "@cometchat/chat-uikit-react"; -import React from "react"; +| Recipe | Code | +| --- | --- | +| Joined groups only | `new CometChat.GroupsRequestBuilder().joinedOnly(true)` | +| Limit to 10 per page | `new CometChat.GroupsRequestBuilder().setLimit(10)` | +| Search by keyword | `new CometChat.GroupsRequestBuilder().setSearchKeyword("design")` | +| Filter by tags | `new CometChat.GroupsRequestBuilder().setTags(["vip"])` | +| With tags data | `new CometChat.GroupsRequestBuilder().withTags(true)` | -const GroupsDemo = () => { - function handleOnSelect(group, selected) { - console.log(group); - //your custom onSelect actions - } +Default page size is 30. The component uses infinite scroll — the next page loads as the user scrolls to the bottom. + +The `searchRequestBuilder` prop accepts a separate `GroupsRequestBuilder` for filtering when the search bar is active. + +```tsx +import { CometChatGroups } from "@cometchat/chat-uikit-react"; +import { CometChat } from "@cometchat/chat-sdk-javascript"; + +function SearchFilteredGroups() { return ( ); -}; - -export default GroupsDemo; +} ``` - - - - -##### 2. onItemClick +Refer to [GroupsRequestBuilder](/sdk/javascript/retrieve-groups) for the full builder API. -The `onItemClick` event is activated when you click on the Group List item. This action does not come with any predefined behavior. However, you have the flexibility to override this event and tailor it to suit your needs using the following code snippet. +--- - - -```ts -import { CometChat } from "@cometchat/chat-sdk-javascript"; -import { CometChatGroups } from "@cometchat/chat-uikit-react"; -import React from "react"; +## Actions and Events -const GroupsDemo = () => { - function handleOnItemClick(group: CometChat.Group): void { - console.log(group, "your custom on item click action"); - } - return ; -}; +### Callback Props -export default GroupsDemo; -``` +#### onItemClick - +Fires when a group row is tapped. Primary navigation hook — set the active group and render the message view. - -```js +```tsx import { CometChatGroups } from "@cometchat/chat-uikit-react"; -import React from "react"; - -const GroupsDemo = () => { - function handleOnItemClick(group) { - console.log(group, "your custom on item click action"); - } - return ; -}; - -export default GroupsDemo; -``` - - - - - -##### 3. onError - -This action doesn't change the behavior of the component but rather listens for any errors that occur in the Groups component. - - - -```ts import { CometChat } from "@cometchat/chat-sdk-javascript"; -import { CometChatGroups } from "@cometchat/chat-uikit-react"; -import React from "react"; - -const GroupsDemo = () => { - const handleOnError = (error: CometChat.CometChatException) => { - console.log("Your custom on error actions"); - }; - return ; -}; - -export default GroupsDemo; -``` - - - - -```js -import { CometChatGroups } from "@cometchat/chat-uikit-react"; -import React from "react"; -const GroupsDemo = () => { - const handleOnError = (error) => { - console.log("Your custom on error actions"); +function GroupsWithClick() { + const handleItemClick = (group: CometChat.Group) => { + console.log("Selected:", group.getGuid()); }; - return ; -}; -export default GroupsDemo; + return ; +} ``` - - - - -### Filters - -**Filters** allow you to customize the data displayed in a list within a Component. You can filter the list based on your specific criteria, allowing for a more customized. Filters can be applied using RequestBuilders of Chat SDK. - -##### 1. GroupsRequestBuilder - -The [GroupsRequestBuilder](/sdk/javascript/retrieve-groups) enables you to filter and customize the group list based on available parameters in [GroupsRequestBuilder](/sdk/javascript/retrieve-groups). This feature allows you to create more specific and targeted queries when fetching groups. The following are the parameters available in [GroupsRequestBuilder](/sdk/javascript/retrieve-groups) +#### onSelect -| Methods | Type | Description | -| -------------------- | -------------- | --------------------------------------------------------------------------------------- | -| **setLimit** | number | sets the number groups that can be fetched in a single request, suitable for pagination | -| **setSearchKeyword** | String | used for fetching groups matching the passed string | -| **joinedOnly** | boolean | to fetch only joined groups. | -| **setTags** | Array\ | used for fetching groups containing the passed tags | -| **withTags** | boolean | used to fetch tags data along with the list of groups | +Fires when a group is checked/unchecked in multi-select mode. Requires `selectionMode` to be set. -**Example** - -In the example below, we are applying a filter to the Group List based on only joined groups and setting the limit to two. - - - -```ts +```tsx +import { useState } from "react"; +import { + CometChatGroups, + SelectionMode, +} from "@cometchat/chat-uikit-react"; import { CometChat } from "@cometchat/chat-sdk-javascript"; -import { CometChatGroups } from "@cometchat/chat-uikit-react"; -import React from "react"; - -const GroupsDemo = () => { - return ( - - ); -}; - -export default GroupsDemo; -``` - +function BatchSelectGroups() { + const [selected, setSelected] = useState>(new Set()); - -```js -import { CometChat } from "@cometchat/chat-sdk-javascript"; -import { CometChatGroups } from "@cometchat/chat-uikit-react"; -import React from "react"; + const handleSelect = (group: CometChat.Group, isSelected: boolean) => { + setSelected((prev) => { + const next = new Set(prev); + const id = group.getGuid(); + isSelected ? next.add(id) : next.delete(id); + return next; + }); + }; -const GroupsDemo = () => { return ( ); -}; - -export default GroupsDemo; +} ``` - - - - -##### 2. SearchRequestBuilder +#### onError -The SearchRequestBuilder uses [GroupsRequestBuilder](/sdk/javascript/retrieve-groups) enables you to filter and customize the search list based on available parameters in GroupsRequestBuilder. This feature allows you to keep uniformity between the displayed Groups List and searched Group List. +Fires on internal errors (network failure, auth issue, SDK exception). -**Example** - - - -```ts -import { CometChat } from "@cometchat/chat-sdk-javascript"; +```tsx import { CometChatGroups } from "@cometchat/chat-uikit-react"; -import React from "react"; +import { CometChat } from "@cometchat/chat-sdk-javascript"; -const GroupsDemo = () => { +function GroupsWithErrorHandler() { return ( { + console.error("CometChatGroups error:", error); + }} /> ); -}; - -export default GroupsDemo; +} ``` - +### Global UI Events + +`CometChatGroupEvents` emits events subscribable from anywhere in the application. Subscribe in a `useEffect` and unsubscribe on cleanup. - -```js +| Event | Fires when | Payload | +| --- | --- | --- | +| `ccGroupCreated` | A new group is created | `CometChat.Group` | +| `ccGroupDeleted` | A group is deleted | `CometChat.Group` | +| `ccGroupMemberJoined` | A user joins a group | `IGroupMemberJoined` | +| `ccGroupLeft` | A user leaves a group | `IGroupLeft` | +| `ccGroupMemberAdded` | Members are added to a group | `IGroupMemberAdded` | +| `ccGroupMemberScopeChanged` | A member's scope changes | `IGroupMemberScopeChanged` | +| `ccGroupMemberKicked` | A member is kicked | `IGroupMemberKickedBanned` | +| `ccGroupMemberBanned` | A member is banned | `IGroupMemberKickedBanned` | +| `ccGroupMemberUnbanned` | A member is unbanned | `IGroupMemberUnBanned` | +| `ccOwnershipChanged` | Group ownership is transferred | `IOwnershipChanged` | + +```tsx +import { useEffect } from "react"; +import { CometChatGroupEvents } from "@cometchat/chat-uikit-react"; import { CometChat } from "@cometchat/chat-sdk-javascript"; -import { CometChatGroups } from "@cometchat/chat-uikit-react"; -import React from "react"; -const GroupsDemo = () => { - return ( - - ); -}; +function useGroupEvents() { + useEffect(() => { + const createdSub = CometChatGroupEvents.ccGroupCreated.subscribe( + (group: CometChat.Group) => { + console.log("Group created:", group.getName()); + } + ); + const deletedSub = CometChatGroupEvents.ccGroupDeleted.subscribe( + (group: CometChat.Group) => { + console.log("Group deleted:", group.getName()); + } + ); + const memberAddedSub = CometChatGroupEvents.ccGroupMemberAdded.subscribe( + (item) => { + console.log("Members added to:", item.userAddedIn.getName()); + } + ); + const leftSub = CometChatGroupEvents.ccGroupLeft.subscribe( + (item) => { + console.log("User left group:", item.leftGroup.getName()); + } + ); -export default GroupsDemo; + return () => { + createdSub?.unsubscribe(); + deletedSub?.unsubscribe(); + memberAddedSub?.unsubscribe(); + leftSub?.unsubscribe(); + }; + }, []); +} ``` - +### SDK Events (Real-Time, Automatic) - +The component listens to these SDK events internally. No manual attachment needed unless additional side effects are required. -*** +| SDK Listener | Internal behavior | +| --- | --- | +| `onGroupMemberJoined` | Updates member count, sets `hasJoined` if current user joined | +| `onGroupMemberLeft` | Updates member count, sets `hasJoined(false)` if current user left | +| `onMemberAddedToGroup` | Updates member count, adds group to list if current user was added | +| `onGroupMemberKicked` | Updates member count, sets `hasJoined(false)` if current user was kicked | +| `onGroupMemberBanned` | Removes group if current user was banned, otherwise updates member count | +| `onGroupMemberScopeChanged` | Updates scope if current user's scope changed, updates member count | -### Events + +In React 18 StrictMode, `useEffect` runs twice on mount in development. The component handles listener cleanup internally, but any additional listeners added alongside the component need cleanup in the `useEffect` return function to avoid duplicate event handling. + -[Events](/ui-kit/react/components-overview#events) are emitted by a `Component`. By using event you can extend existing functionality. Being global events, they can be applied in Multiple Locations and are capable of being Added or Removed. +--- -To handle events supported by Groups you have to add corresponding listeners by using `CometChatGroupEvents` +## Custom View Slots -The `Groups` component does not produce any events directly. +Each slot replaces a section of the default UI. Slots that accept a group parameter receive the `CometChat.Group` object for that row. -*** +| Slot | Signature | Replaces | +| --- | --- | --- | +| `itemView` | `(group: CometChat.Group) => JSX.Element` | Entire list item row | +| `leadingView` | `(group: CometChat.Group) => JSX.Element` | Avatar / left section | +| `titleView` | `(group: CometChat.Group) => JSX.Element` | Name / title text | +| `subtitleView` | `(group: CometChat.Group) => JSX.Element` | Member count subtitle | +| `trailingView` | `(group: CometChat.Group) => JSX.Element` | Right section | +| `headerView` | `JSX.Element` | Entire header bar | +| `loadingView` | `JSX.Element` | Loading spinner | +| `emptyView` | `JSX.Element` | Empty state | +| `errorView` | `JSX.Element` | Error state | +| `options` | `(group: CometChat.Group) => CometChatOption[]` | Context menu / hover actions | -## Customization +### itemView -To fit your app's design requirements, you can customize the appearance of the Groups component. We provide exposed methods that allow you to modify the experience and behavior according to your specific needs. +Replace the entire list item row. -### Style +Default: -Using CSS you can customize the look and feel of the component in your app like the color, size, shape, and fonts. + + + -**Example** +Customized: - + -```ts -import { CometChatGroups } from "@cometchat/chat-uikit-react"; -import React from "react"; - -const GroupsDemo = () => { - return ; -}; - -export default GroupsDemo; -``` - - - - -```js +```tsx +import { CometChat } from "@cometchat/chat-sdk-javascript"; import { CometChatGroups } from "@cometchat/chat-uikit-react"; -import React from "react"; -const GroupsDemo = () => { - return ; -}; +function CustomItemViewGroups() { + const getItemView = (group: CometChat.Group) => { + return ( +
+
+
{group.getName()}
+
JOIN
+
+
+ {group.getMembersCount()} Members • {group.getDescription()} +
+
+ ); + }; -export default GroupsDemo; + return ; +} ``` -
- - + ```css -.cometchat .cometchat-groups .cometchat-list__header-title { - background-color: #edeafa; - color: #6852d6; - border-width: 0px 1px 1px 0px; - border-style: solid; - border-color: #6852d6; - overflow: hidden; - text-overflow: ellipsis; - font-family: "Times New Roman"; - font-size: 24px; - font-style: normal; - font-weight: 700; - line-height: 28.8px; -} - -.cometchat .cometchat-groups .cometchat-search-bar__input::placeholder { - font-family: "Times New Roman"; - font-size: 16px; - font-style: normal; - font-weight: 400; - line-height: 19.2px; +.group-list-item { + display: flex; + flex-direction: column; + text-align: left; + min-width: 240px; + padding: 8px 16px; + gap: 4px; + flex: 1 0 0; + border-right: 1px solid #f5f5f5; + background: #fff; } -.cometchat .cometchat-groups .cometchat-list-item { - background: #fff; - border-right: 1px solid #f5f5f5; +.group-list-item:hover { + background-color: #f5f5f5; } -.cometchat .cometchat-groups__list-item .cometchat-avatar { - background-color: #aa9ee8; - border-radius: 6.67px; +.group-list-item__title-wrapper { + display: flex; + justify-content: space-between; + align-items: center; + align-self: stretch; } -.cometchat .cometchat-groups .cometchat-list-item__body-title { +.group-list-item__title { overflow: hidden; color: #141414; text-overflow: ellipsis; - font-family: "Times New Roman"; - font-size: 16px; - font-style: normal; - font-weight: 400; - line-height: 19.2px; + font: 500 16px Roboto; } -.cometchat .cometchat-groups .cometchat-groups__subtitle { +.group-list-item__tail { + display: flex; + padding: 4px 12px; + justify-content: center; + align-items: center; + border-radius: 1000px; + background: #edeafa; overflow: hidden; - color: #727272; + color: #6852d6; text-overflow: ellipsis; - white-space: nowrap; - font-family: "Times New Roman"; - font-size: 14px; - font-style: normal; - font-weight: 400; - line-height: 16.8px; + font: 700 12px Roboto; } -``` - - - -
- -*** - -### Functionality - -These are a set of small functional customizations that allow you to fine-tune the overall experience of the component. With these, you can change text, set custom icons, and toggle the visibility of UI elements. - - - -```ts -import { CometChatGroups, TitleAlignment } from "@cometchat/chat-uikit-react"; -import React from "react"; - -const GroupsDemo = () => { - return ( - - ); -}; - -export default GroupsDemo; -``` - - - - -```js -import { CometChatGroups, TitleAlignment } from "@cometchat/chat-uikit-react"; -import React from "react"; - -const GroupsDemo = () => { - return ( - - ); -}; -export default GroupsDemo; +.group-list-item__subtitle { + overflow: hidden; + color: #727272; + text-overflow: ellipsis; + white-space: nowrap; + font: 400 14px Roboto; +} ``` - - -Below is a list of customizations along with corresponding code snippets: - -| Property | Description | Code | -| ------------------- | ------------------------------------------------------------------- | ---------------------------------------- | -| **Hide Search** | Hides the default search bar. | `hideSearch={true}` | -| **Hide Error** | Hides the default and custom error view passed in `errorView` prop. | `hideError={true}` | -| **Hide Group Type** | Hides the group type icon. | `hideGroupType={true}` | -| **Active Group** | The group to highlight in the list. | `activeGroup={chatGroup}` | -| **Selection Mode** | Selection mode to use for the default trailing view. | `selectionMode={SelectionMode.multiple}` | -| **Show Scrollbar** | Controls the visibility of the scrollbar in the list. | `showScrollbar={true}` | -| **Loading View** | A custom view to display during the loading state. | `loadingView={<>Custom Loading View}` | -| **Empty View** | Custom view for the empty state of the component. | `emptyView={<>Custom Empty View}` | -| **Error View** | A custom view to display when an error occurs. | `errorView={<>Custom Error View}` | - -*** - -### Advanced - -For advanced-level customization, you can set custom views to the component. This lets you tailor each aspect of the component to fit your exact needs and application aesthetics. You can create and define your views, layouts, and UI elements and then incorporate those into the component. +### titleView -*** - -#### ItemView - -A custom view to render for each group in the fetched list. - -Shown below is the default chat interface. - - - - - -The customized chat interface is displayed below. +Replace the name / title text. Group type badge inline example. - + -Use the following code to achieve the customization shown above. - -```ts +```tsx import { CometChat } from "@cometchat/chat-sdk-javascript"; import { CometChatGroups } from "@cometchat/chat-uikit-react"; -import React from "react"; - -const GroupsDemo = () => { - const getItemView = (group: CometChat.Group) => { - return ( -
-
-
{group.getName()}
-
JOIN
-
-
- {group.getMembersCount()} Members • {group.getDescription()} -
-
- ); - }; - - return ; -}; - -export default GroupsDemo; -``` - -
- - -```js -import { CometChatGroups } from "@cometchat/chat-uikit-react"; -import React from "react"; -const GroupsDemo = () => { - const getItemView = (group: CometChat.Group) => { +function GroupTypeTitleGroups() { + const getTitleView = (group: CometChat.Group) => { return ( -
-
-
{group.getName()}
-
JOIN
-
-
- {group.getMembersCount()} Members • {group.getDescription()} -
+
+ {group.getName()} + {group.getType()}
); }; - return ; -}; - -export default GroupsDemo; + return ; +} ``` - - - + ```css -.group-list-item { - display: flex; - flex-direction: column; - text-align: left; - display: flex; - min-width: 240px; - padding: 8px 16px; - gap: 4px; - flex: 1 0 0; - border-right: 1px solid #f5f5f5; - background: #fff; -} - -.group-list-item:hover { - background-color: #f5f5f5; -} - -.group-list-item__title-wrapper { +.groups__title-view { display: flex; - justify-content: space-between; align-items: center; + gap: 4px; align-self: stretch; } -.group-list-item__title { +.groups__title-view-name { overflow: hidden; color: #141414; text-overflow: ellipsis; - font-family: Roboto; - font-size: var(--Size-H4, 16px); - font-style: normal; - font-weight: 500; - line-height: 19.2px; + font: 500 16px Roboto; } -.group-list-item__tail { +.groups__title-view-type { + color: #fff; + font: 600 8px Roboto; display: flex; - padding: 4px 12px; + height: 15px; + padding: 1px 3px; justify-content: center; align-items: center; - gap: 20px; - border-radius: 1000px; - background: #edeafa; - overflow: hidden; - color: #6852d6; - text-overflow: ellipsis; - font-family: Roboto; - font-size: 12px; - font-style: normal; - font-weight: 700; - line-height: 14.4px; -} - -.group-list-item__subtitle { - overflow: hidden; - color: #727272; - text-overflow: ellipsis; - white-space: nowrap; - font-family: Roboto; - font-size: 14px; - font-style: normal; - font-weight: 400; - line-height: 16.8px; -} -``` - - - - - -*** - -#### TitleView - -The customized chat interface is displayed below. - - - - - -Use the following code to achieve the customization shown above. - - - -```ts -import React from "react"; -import { CometChat } from "@cometchat/chat-sdk-javascript"; -import { CometChatGroups } from "@cometchat/chat-uikit-react"; - -// Custom title view component -const customTitleView = (group: CometChat.Group) => { - return
- {group.getName()} - {group.getType()} -
; + gap: 4px; + border-radius: 7px; + background: #09c26f; } -; -``` - -
- - -```css -.groups__title-view{ -display: flex; -align-items: center; -gap: 4px; -align-self: stretch; -} -.groups__title-view-name{ -overflow: hidden; -color: #141414; -text-overflow: ellipsis; -font:500 16px Roboto -} -.groups__title-view-type{ -color: #FFF; -font: 600 8px Roboto; -display: flex; -height: 15px; -padding: 1px 3px; -justify-content: center; -align-items: center; -gap: 4px; -border-radius: 7px; -background: #09C26F; -} -.groups__title-view-public .groups__title-view-type{ -background: #0B7BEA; -} -.groups__title-view-type img{ -background: #fff; -border-radius: 4px; -height: 12px; -width: 12px; +.groups__title-view-public .groups__title-view-type { + background: #0b7bea; } ``` - -
-*** +### subtitleView -#### SubtitleView +Replace the member count subtitle text. -Custom subtitle view to be rendered for each group in the fetched list. - -Shown below is the default chat interface. +Default: -The customized chat interface is displayed below. +Customized: -Use the following code to achieve the customization shown above. - -```ts -import { CometChat } from "@cometchat/chat-sdk-javascript"; -import { CometChatGroups } from "@cometchat/chat-uikit-react"; -import React from "react"; - -const GroupsDemo = () => { - const getSubtitleView = (group: CometChat.Group): JSX.Element => { - if (!(group instanceof CometChat.Group)) { - return <>; - } - - return ( -
- {group.getMembersCount()} Members • {group.getDescription()} -
- ); - }; - - return ; -}; - -export default GroupsDemo; -``` - -
- - -```js +```tsx import { CometChat } from "@cometchat/chat-sdk-javascript"; import { CometChatGroups } from "@cometchat/chat-uikit-react"; -import React from "react"; - -const GroupsDemo = () => { - const getSubtitleView = (group) => { - if (!(group instanceof CometChat.Group)) { - return <>; - } +function SubtitleGroups() { + const getSubtitleView = (group: CometChat.Group) => { return (
{group.getMembersCount()} Members • {group.getDescription()} @@ -797,333 +625,721 @@ const GroupsDemo = () => { }; return ; -}; - -export default GroupsDemo; +} ``` - - - + ```css .cometchat .cometchat-groups .group-subtitle { overflow: hidden; color: #727272; text-overflow: ellipsis; white-space: nowrap; - font-size: 14px; - font-style: normal; - font-weight: 400; - line-height: 120%; + font: 400 14px Roboto; } ``` - - -*** +### leadingView -#### LeadingView - -The customized chat interface is displayed below. +Replace the avatar / left section. Joined status badge example. -Use the following code to achieve the customization shown above. - -```ts -import React from "react"; +```tsx import { CometChat } from "@cometchat/chat-sdk-javascript"; -import { CometChatGroups,CometChatAvatar } from "@cometchat/chat-uikit-react"; - -// Custom leading view component - const customLeadingView = (group: CometChat.Group) => { - return <> - {group.getHasJoined() ?
- - {/* Icon here */} - Joined - - -
:
- - {/* Icon here */} - Join - - -
}; - } +import { CometChatGroups, CometChatAvatar } from "@cometchat/chat-uikit-react"; -; -``` +function LeadingViewGroups() { + const getLeadingView = (group: CometChat.Group) => { + return ( + <> + {group.getHasJoined() ? ( +
+ + Joined +
+ ) : ( +
+ + Join +
+ )} + + ); + }; + return ; +} +```
- - + ```css - -.cometchat-groups .cometchat-list-item .groups__leading-view .cometchat-avatar__image, .cometchat-groups .cometchat-list-item .groups__leading-view .cometchat-avatar{ +.cometchat-groups .cometchat-list-item .groups__leading-view .cometchat-avatar__image, +.cometchat-groups .cometchat-list-item .groups__leading-view .cometchat-avatar { border-radius: 8px; - height: 48px ; - width: 48px ; + height: 48px; + width: 48px; } -.groups__leading-view-info{ +.groups__leading-view-info { display: flex; width: 48px; height: 15px; padding: 1px 3px; justify-content: center; align-items: center; - color:#FFF; - font:600 8px/9.6px Roboto; - background:#FFAB00; - position:absolute; - bottom:-2px; + color: #fff; + font: 600 8px/9.6px Roboto; + background: #ffab00; + position: absolute; + bottom: -2px; } -.groups__leading-view-joined .groups__leading-view-info{ - background:#09C26F; + +.groups__leading-view-joined .groups__leading-view-info { + background: #09c26f; } -.groups__leading-view{ + +.groups__leading-view { position: relative; } ``` - -
-*** +### trailingView -#### TrailingView - -The customized chat interface is displayed below. +Replace the right section. Join status button example. -Use the following code to achieve the customization shown above. - -```ts -import React from "react"; +```tsx import { CometChat } from "@cometchat/chat-sdk-javascript"; -import { - CometChatGroups, -} from "@cometchat/chat-uikit-react"; +import { CometChatGroups } from "@cometchat/chat-uikit-react"; -// Custom trailing view component -const customTrailingButtonView = (group:CometChat.Group) => { -return
- {group.getHasJoined() ? "JOINED" : "+ JOIN"} -
-} +function TrailingViewGroups() { + const getTrailingView = (group: CometChat.Group) => { + return ( +
+ {group.getHasJoined() ? "JOINED" : "+ JOIN"} +
+ ); + }; -; + return ; +} ``` -
- - + ```css -.groups__trailing-view{ -display: flex; -padding: 4px 12px; -justify-content: center; -align-items: center; -border-radius: 1000px; -background: #EDEAFA; -overflow: hidden; -color: #6852D6; -text-overflow: ellipsis; -font:700 12px Roboto; +.groups__trailing-view { + display: flex; + padding: 4px 12px; + justify-content: center; + align-items: center; + border-radius: 1000px; + background: #edeafa; + overflow: hidden; + color: #6852d6; + text-overflow: ellipsis; + font: 700 12px Roboto; } -.cometchat-groups .cometchat-list-item__trailing-view{ -width: fit-content; -height: fit-content; + +.cometchat-groups .cometchat-list-item__trailing-view { + width: fit-content; + height: fit-content; } ``` - -
-*** +### headerView -#### Header View - -A custom component to render in the top-right corner of the groups list. - -The customized chat interface is displayed below. +Replace the entire header bar. -Use the following code to achieve the customization shown above. - -```ts -import { CometChatGroups } from "@cometchat/chat-uikit-react"; -import React from "react"; +```tsx +import { + CometChatButton, + CometChatGroups, + getLocalizedString, +} from "@cometchat/chat-uikit-react"; -const GroupsDemo = () => { - const getHeaderView = () => { - return
; - }; +function CustomHeaderGroups() { + return ( + +
+ {getLocalizedString("GROUPS")} +
+ { /* handle click */ }} /> +
+ } + /> + ); +} +``` +
+ +```css +.groups__header { + display: flex; + width: 100%; + padding: 8px 16px; + align-items: center; + justify-content: space-between; + gap: 12px; + border-radius: 10px; + border: 1px solid #e8e8e8; + background: #edeafa; +} - return ; -}; +.groups__header__title { + overflow: hidden; + color: #141414; + text-overflow: ellipsis; + font: 700 24px Roboto; +} -export default GroupsDemo; +.groups__header .cometchat-button .cometchat-button__icon { + background: #141414; +} + +.groups__header .cometchat-button { + width: 24px; + border: none; + background: transparent; + border-radius: 0; +} +``` + +
+ +### options + +Replace the context menu / hover actions on each group item. + + + + + + + +```tsx +import { CometChat } from "@cometchat/chat-sdk-javascript"; +import { + CometChatOption, + CometChatGroups, +} from "@cometchat/chat-uikit-react"; + +function CustomOptionsGroups() { + const getOptions = (group: CometChat.Group) => [ + new CometChatOption({ + title: "Delete", + id: "delete", + onClick: () => { /* delete logic */ }, + }), + ]; + + return ; +} ``` + + +```css +.cometchat .cometchat-groups .cometchat-menu-list__menu { + background: none; +} +.cometchat .cometchat-groups .cometchat-menu-list__main-menu-item-icon { + background: #f44649; +} +``` + + +```ts +// CometChatOption interface +interface CometChatOption { + id?: string; // Unique identifier + title?: string; // Display text + iconURL?: string; // Icon asset URL + onClick?: () => void; // Click handler +} +``` + +--- - -```js +## Common Patterns + +### Custom empty state with CTA + +```tsx import { CometChatGroups } from "@cometchat/chat-uikit-react"; -import React from "react"; -const GroupsDemo = () => { - const getHeaderView = () => { - return
; - }; +function EmptyStateGroups() { + return ( + +

No groups available

+ +
+ } + /> + ); +} +``` - return ; -}; +### Hide all chrome — minimal list -export default GroupsDemo; +```tsx +import { CometChatGroups } from "@cometchat/chat-uikit-react"; + +function MinimalGroups() { + return ( + + ); +} ``` -
+### Joined groups only - -```css -.group-header-view { - height: 24px; - width: 24px; - display: flex; - align-items: center; - justify-content: center; - border: none; - align-self: center; - background: #6852d6; - flex-shrink: 0; - -webkit-mask: url("../assets/create-group.svg") center center no-repeat; - mask: url("../assets/create-group.svg") center center no-repeat; - -webkit-mask-size: contain; - mask-size: contain; +```tsx +import { CometChatGroups } from "@cometchat/chat-uikit-react"; +import { CometChat } from "@cometchat/chat-sdk-javascript"; + +function JoinedGroups() { + return ( + + ); } ``` - +--- - +## CSS Architecture -*** +The component uses CSS custom properties (design tokens) defined in `@cometchat/chat-uikit-react/css-variables.css`. The cascade: -#### Options +1. Global tokens (e.g., `--cometchat-primary-color`, `--cometchat-background-color-01`) are set on the `.cometchat` root wrapper. +2. Component CSS (`.cometchat-groups`) consumes these tokens via `var()` with fallback values. +3. Overrides target `.cometchat-groups` descendant selectors in a global stylesheet. -You can set the Custom options to the Groups component. +To scope overrides to a single instance when multiple `CometChatGroups` exist on the same page, wrap the component in a container and scope selectors: -The customized chat interface is displayed below. +```css +.sidebar-left .cometchat-groups .cometchat-avatar { + border-radius: 8px; +} +``` + +### Key Selectors + +| Target | Selector | +| --- | --- | +| Root | `.cometchat-groups` | +| Header title | `.cometchat-groups .cometchat-list__header-title` | +| Search bar input | `.cometchat-groups .cometchat-search-bar__input` | +| List item | `.cometchat-groups .cometchat-list-item` | +| Body title | `.cometchat-groups .cometchat-list-item__body-title` | +| Avatar | `.cometchat-groups__list-item .cometchat-avatar` | +| Subtitle | `.cometchat-groups__subtitle` | +| Active item | `.cometchat-groups__list-item-active .cometchat-list-item` | +| Password group icon | `.cometchat-groups__list-item-password .cometchat-list-item__status` | +| Private group icon | `.cometchat-groups__list-item-private .cometchat-list-item__status` | +| Empty state | `.cometchat-groups__empty-state-view` | +| Error state | `.cometchat-groups__error-state-view` | +| Shimmer loading | `.cometchat-groups__shimmer` | + +### Example: Brand-themed groups - + -Use the following code to achieve the customization shown above. +```css +.cometchat-groups .cometchat-list__header-title { + background-color: #edeafa; + color: #6852d6; + border-width: 0px 1px 1px 0px; + border-style: solid; + border-color: #6852d6; + font-family: "Times New Roman"; + font-size: 24px; + font-weight: 700; +} - - -```ts -import { CometChatGroups, CometChatOption } from "@cometchat/chat-uikit-react"; -import React from "react"; - -const GroupsDemo = () => { - const getOptions = (group: CometChat.Group): CometChatOption[] => { - return [ - new CometChatOption({ - id: "delete", - title: "delete", - onClick: () => { - console.log("Custom option clicked for group:", group); - }, - }), - ]; - }; +.cometchat-groups__list-item .cometchat-avatar { + background-color: #aa9ee8; + border-radius: 6.67px; +} - return ; -}; +.cometchat-groups .cometchat-list-item__body-title { + font-family: "Times New Roman"; + font-size: 16px; + font-weight: 400; +} -export default GroupsDemo; +.cometchat-groups .cometchat-groups__subtitle { + font-family: "Times New Roman"; + font-size: 14px; + font-weight: 400; +} ``` - +### Customization Matrix - -```js -import { CometChatGroups, CometChatOption } from "@cometchat/chat-uikit-react"; -import React from "react"; - -const GroupsDemo = () => { - const getOptions = (group: CometChat.Group): CometChatOption[] => { - return [ - new CometChatOption({ - id: "delete", - title: "delete", - onClick: () => { - console.log("Custom option clicked for group:", group); - }, - }), - ]; - }; +| What to change | Where | Property/API | Example | +| --- | --- | --- | --- | +| Override behavior on user interaction | Component props | `on` callbacks | `onItemClick={(g) => setActive(g)}` | +| Filter which groups appear | Component props | `groupsRequestBuilder` | `groupsRequestBuilder={new CometChat.GroupsRequestBuilder().joinedOnly(true)}` | +| Toggle visibility of UI elements | Component props | `hide` boolean props | `hideGroupType={true}` | +| Replace a section of the list item | Component props | `View` render props | `itemView={(group) =>
...
}` | +| Change colors, fonts, spacing | Global CSS | Target `.cometchat-groups` class | `.cometchat-groups .cometchat-avatar { border-radius: 8px; }` | - return ; -}; +--- -export default GroupsDemo; -``` +## Accessibility -
+The component renders a scrollable list of interactive items. Each group row is keyboard-focusable and activates on Enter/Space. The context menu (options) is accessible via keyboard. Avatar images include the group name as alt text. Group type indicators (public/private/password) use CSS mask images — add `aria-label` attributes via `itemView` if screen reader descriptions are needed for these visual indicators. - -```css -.cometchat .cometchat-groups .cometchat-menu-list__menu { - background: none; +--- + +--- + +## Props + +All props are optional unless noted otherwise. + +--- + +### activeGroup + +Highlights the specified group in the list. + +| | | +| --- | --- | +| Type | `CometChat.Group` | +| Default | `undefined` | + +Must be a reference-equal object from the SDK; a manually constructed object will not match. + +--- + +### emptyView + +Custom component displayed when there are no groups. + +| | | +| --- | --- | +| Type | `JSX.Element` | +| Default | Built-in empty state | + +--- + +### errorView + +Custom component displayed when an error occurs. + +| | | +| --- | --- | +| Type | `JSX.Element` | +| Default | Built-in error state | + +Hidden when `hideError={true}`. + +--- + +### groupsRequestBuilder + +Controls which groups load and in what order. + +| | | +| --- | --- | +| Type | `CometChat.GroupsRequestBuilder` | +| Default | SDK default (30 per page) | + +Pass the builder instance, not the result of `.build()`. + +--- + +### headerView + +Custom component rendered as the entire header bar. + +| | | +| --- | --- | +| Type | `JSX.Element` | +| Default | Built-in header with title | + +--- + +### hideError + +Hides the default and custom error views. + +| | | +| --- | --- | +| Type | `boolean` | +| Default | `false` | + +Also suppresses `errorView` if set. + +--- + +### hideGroupType + +Hides the group type icon (public/private/password). + +| | | +| --- | --- | +| Type | `boolean` | +| Default | `false` | + +--- + +### hideSearch + +Hides the default search bar. + +| | | +| --- | --- | +| Type | `boolean` | +| Default | `false` | + +--- + +### itemView + +Custom renderer for the entire list item row. + +| | | +| --- | --- | +| Type | `(group: CometChat.Group) => JSX.Element` | +| Default | Built-in list item | + +--- + +### leadingView + +Custom renderer for the avatar / left section. + +| | | +| --- | --- | +| Type | `(group: CometChat.Group) => JSX.Element` | +| Default | Built-in avatar | + +--- + +### loadingView + +Custom component displayed during the loading state. + +| | | +| --- | --- | +| Type | `JSX.Element` | +| Default | Built-in shimmer | + +--- + +### onError + +Callback fired when the component encounters an error. + +| | | +| --- | --- | +| Type | `((error: CometChat.CometChatException) => void) \| null` | +| Default | `undefined` | + +--- + +### onItemClick + +Callback fired when a group row is clicked. + +| | | +| --- | --- | +| Type | `(group: CometChat.Group) => void` | +| Default | `undefined` | + +--- + +### onSelect + +Callback fired when a group is selected/deselected. Requires `selectionMode` to be set. + +| | | +| --- | --- | +| Type | `(group: CometChat.Group, selected: boolean) => void` | +| Default | `undefined` | + +--- + +### options + +Custom context menu / hover actions for each group item. + +| | | +| --- | --- | +| Type | `(group: CometChat.Group) => CometChatOption[]` | +| Default | `undefined` | + +```ts +class CometChatOption { + id?: string; + title?: string; + iconURL?: string; + onClick?: () => void; } -.cometchat .cometchat-groups .cometchat-menu-list__main-menu-item-icon { - height: 24px; - width: 24px; - display: flex; - align-items: center; - justify-content: center; - border: none; - align-self: center; - background: #f44649; - flex-shrink: 0; - -webkit-mask: url("../assets/delete.svg") center center no-repeat; - mask: url("../assets/delete.svg") center center no-repeat; - -webkit-mask-size: contain; - mask-size: contain; +``` + +--- + +### searchRequestBuilder + +Controls filtering when the search bar is active. + +| | | +| --- | --- | +| Type | `CometChat.GroupsRequestBuilder` | +| Default | `undefined` | + +--- + +### selectionMode + +Enables single or multi-select checkboxes on list items. + +| | | +| --- | --- | +| Type | `SelectionMode` | +| Default | `SelectionMode.none` | + +```ts +enum SelectionMode { + single, // 0 + multiple, // 1 + none, // 2 } ``` - +Must pair with `onSelect` to capture selections. -
+--- + +### showScrollbar + +Shows the scrollbar in the group list. + +| | | +| --- | --- | +| Type | `boolean` | +| Default | `false` | + +--- + +### subtitleView + +Custom renderer for the member count subtitle text. + +| | | +| --- | --- | +| Type | `(group: CometChat.Group) => JSX.Element` | +| Default | Built-in subtitle | + +--- + +### titleView + +Custom renderer for the name / title text. + +| | | +| --- | --- | +| Type | `(group: CometChat.Group) => JSX.Element` | +| Default | Built-in title | + +--- + +### trailingView + +Custom renderer for the right section. + +| | | +| --- | --- | +| Type | `(group: CometChat.Group) => JSX.Element` | +| Default | Built-in trailing view | + +--- + +## Events + +| Event | Payload | Fires when | +| --- | --- | --- | +| `CometChatGroupEvents.ccGroupCreated` | `CometChat.Group` | New group created | +| `CometChatGroupEvents.ccGroupDeleted` | `CometChat.Group` | Group deleted | +| `CometChatGroupEvents.ccGroupMemberJoined` | `IGroupMemberJoined` | User joins a group | +| `CometChatGroupEvents.ccGroupLeft` | `IGroupLeft` | User leaves a group | +| `CometChatGroupEvents.ccGroupMemberAdded` | `IGroupMemberAdded` | Members added to a group | +| `CometChatGroupEvents.ccGroupMemberScopeChanged` | `IGroupMemberScopeChanged` | Member scope changed | +| `CometChatGroupEvents.ccGroupMemberKicked` | `IGroupMemberKickedBanned` | Member kicked | +| `CometChatGroupEvents.ccGroupMemberBanned` | `IGroupMemberKickedBanned` | Member banned | +| `CometChatGroupEvents.ccGroupMemberUnbanned` | `IGroupMemberUnBanned` | Member unbanned | +| `CometChatGroupEvents.ccOwnershipChanged` | `IOwnershipChanged` | Ownership transferred | + +All events are RxJS `Subject` instances. Subscribe with `.subscribe()`, unsubscribe with the returned subscription's `.unsubscribe()`. + +--- + +## CSS Selectors + +| Target | Selector | +| --- | --- | +| Root | `.cometchat-groups` | +| Header title | `.cometchat-groups .cometchat-list__header-title` | +| Search bar input | `.cometchat-groups .cometchat-search-bar__input` | +| List item | `.cometchat-groups .cometchat-list-item` | +| Body title | `.cometchat-groups .cometchat-list-item__body-title` | +| Avatar | `.cometchat-groups__list-item .cometchat-avatar` | +| Leading view | `.cometchat-groups__list-item .cometchat-list-item__leading-view` | +| Subtitle | `.cometchat-groups__subtitle` | +| Active item | `.cometchat-groups__list-item-active .cometchat-list-item` | +| Password group icon | `.cometchat-groups__list-item-password .cometchat-list-item__status` | +| Password group status icon | `.cometchat-groups__list-item-password .cometchat-list-item__status-icon` | +| Private group icon | `.cometchat-groups__list-item-private .cometchat-list-item__status` | +| Private group status icon | `.cometchat-groups__list-item-private .cometchat-list-item__status-icon` | +| Empty state | `.cometchat-groups__empty-state-view` | +| Empty state title | `.cometchat-groups__empty-state-view-body-title` | +| Empty state description | `.cometchat-groups__empty-state-view-body-description` | +| Error state | `.cometchat-groups__error-state-view` | +| Error state title | `.cometchat-groups__error-state-view-body-title` | +| Error state description | `.cometchat-groups__error-state-view-body-description` | +| Shimmer loading | `.cometchat-groups__shimmer` | +| Shimmer item | `.cometchat-groups__shimmer-item` | +| Shimmer avatar | `.cometchat-groups__shimmer-item-avatar` | +| Shimmer title | `.cometchat-groups__shimmer-item-body-title` | +| Shimmer subtitle | `.cometchat-groups__shimmer-item-body-subtitle` | diff --git a/ui-kit/react/guide-block-unblock-user.mdx b/ui-kit/react/guide-block-unblock-user.mdx index f758f45b3..d81e39f30 100644 --- a/ui-kit/react/guide-block-unblock-user.mdx +++ b/ui-kit/react/guide-block-unblock-user.mdx @@ -1,8 +1,20 @@ --- title: "Block/Unblock Users" sidebarTitle: "Block/Unblock Users" +description: "Implement block and unblock user functionality in CometChat React UI Kit with composer state management." --- + +- **Package:** `@cometchat/chat-uikit-react` +- **Key components:** `CometChatMessages` — uses `CometChat.blockUsers()` / `CometChat.unblockUsers()` SDK methods +- **Required setup:** `CometChatUIKit.init(UIKitSettings)` then `CometChatUIKit.login("UID")` +- **Events:** `CometChatUserEvents.ccUserBlocked`, `CometChatUserEvents.ccUserUnblocked` +- **UI helpers:** `CometChatConfirmDialog`, `CometChatToast` +- **Sample app:** [GitHub](https://github.com/cometchat/cometchat-uikit-react/tree/v6/sample-app) +- **Related:** [All Guides](/ui-kit/react/guide-overview) + + + Implement user blocking functionality to prevent unwanted communication in your React chat app. ## Overview @@ -17,11 +29,9 @@ The Block Users feature allows users to prevent specific users from sending them ## Prerequisites -- React v18.2.0+ -- CometChat React UI Kit v6.1.0+ -- CometChat Chat SDK JavaScript v4.0.13+ -- Project setup with initialized CometChat credentials (App ID, Auth Key, Region) -- TypeScript support (recommended) +See [Prerequisites](/ui-kit/react/guide-overview#prerequisites). Additional requirements: + +- TypeScript support (recommended) - User authentication and chat functionality already implemented --- @@ -279,11 +289,21 @@ CometChat.blockUsers([UID]).then( --- -## Next Steps & Further Reading - -- [CometChat React UI Kit Documentation](https://www.cometchat.com/docs/ui-kit/react/overview) -- [Sample App Repository](https://github.com/cometchat/cometchat-uikit-react/tree/v6/sample-app) -- User Management Features -- Advanced Customization Guide -- Event Handling Documentation - +## Next Steps + + + + Display and manage user lists. + + + Customize the message input component. + + + Browse all feature and formatter guides. + + + Full working sample application on GitHub. + + + +*** diff --git a/ui-kit/react/guide-call-log-details.mdx b/ui-kit/react/guide-call-log-details.mdx index a029b601e..c80b4f601 100644 --- a/ui-kit/react/guide-call-log-details.mdx +++ b/ui-kit/react/guide-call-log-details.mdx @@ -1,9 +1,20 @@ --- title: "Call Log Details" sidebarTitle: "Call Log Details" +description: "Build a detailed call insights screen with metadata, participants, and recordings in CometChat React UI Kit." --- -Display comprehensive call information and history when users select calls from the calls tab in your React chat app. + +- **Packages:** `@cometchat/chat-uikit-react` + `@cometchat/calls-sdk-javascript` +- **Key components:** `CometChatCallDetails`, `CometChatCallDetailsInfo`, `CometChatCallDetailsParticipants`, `CometChatCallDetailsRecording` +- **Required setup:** `CometChatUIKit.init(UIKitSettings)` then `CometChatUIKit.login("UID")` + Calls SDK installed +- **Purpose:** Detailed call insights screen with metadata, participants, and recordings +- **Sample app:** [GitHub](https://github.com/cometchat/cometchat-uikit-react/tree/v6/sample-app) +- **Related:** [All Guides](/ui-kit/react/guide-overview) + + + +Display complete call information and history when users select calls from the calls tab in your React chat app. ## Overview @@ -17,13 +28,11 @@ The Calls Log Details feature provides users with detailed information about spe ## Prerequisites -- React v18.2.0+ -- CometChat React UI Kit v6.1.0+ -- CometChat Chat SDK JavaScript v4.0.13+ -- CometChat Calls SDK JavaScript v4.0.11+ -- Project setup with initialized CometChat credentials (App ID, Auth Key, Region) -- TypeScript support (recommended) -- Call functionality implemented +See [Prerequisites](/ui-kit/react/guide-overview#prerequisites). Additional requirements: + +- CometChat Calls SDK JavaScript v4.0.11+ +- TypeScript support (recommended) +- Call functionality implemented - Calls tab navigation configured --- @@ -303,3 +312,22 @@ useEffect(() => { | Call history | `CometChatCallDetailsHistory` | [CometChatCallLogHistory.tsx](https://github.com/cometchat/cometchat-uikit-react/blob/v6/sample-app/src/components/CometChatCallLog/CometChatCallLogHistory.tsx) | | Tab navigation | `activeTab` state | [CometChatCallLogDetails.tsx](https://github.com/cometchat/cometchat-uikit-react/blob/v6/sample-app/src/components/CometChatCallLog/CometChatCallLogDetails.tsx) | | User status monitoring| `CometChat.addUserListener()` | [CometChatCallLogDetails.tsx](https://github.com/cometchat/cometchat-uikit-react/blob/v6/sample-app/src/components/CometChatCallLog/CometChatCallLogDetails.tsx) | + +## Next Steps + + + + The call logs component reference. + + + Overview of calling capabilities. + + + Browse all feature and formatter guides. + + + Full working sample application on GitHub. + + + +*** diff --git a/ui-kit/react/guide-group-chat.mdx b/ui-kit/react/guide-group-chat.mdx index b62e735ec..9d1acc21a 100644 --- a/ui-kit/react/guide-group-chat.mdx +++ b/ui-kit/react/guide-group-chat.mdx @@ -1,11 +1,20 @@ --- title: "Group Chat" sidebarTitle: "Group Chat" +description: "Implement group management including create, join, members, roles, and ownership transfer in CometChat React UI Kit." --- -Implement comprehensive group management functionality including creation, joining, member management, and administrative controls in your React chat app. + +- **Package:** `@cometchat/chat-uikit-react` +- **Key components:** `CometChatGroups`, `CometChatGroupMembers`, `CometChatCreateGroup`, `CometChatJoinGroup` +- **Required setup:** `CometChatUIKit.init(UIKitSettings)` then `CometChatUIKit.login("UID")` +- **Features:** Create public/private/password-protected groups, manage members, roles, ownership transfer +- **Sample app:** [GitHub](https://github.com/cometchat/cometchat-uikit-react/tree/v6/sample-app) +- **Related:** [All Guides](/ui-kit/react/guide-overview) + ---- + +Implement complete group management functionality including creation, joining, member management, and administrative controls in your React chat app. ## Overview @@ -15,19 +24,13 @@ Groups Management provides a complete set of features for creating, managing, an - Enables users to create collaborative spaces, manage team communications, control access through different group types, and maintain group organization through administrative tools. - Your app will support full group lifecycle management from creation to administration, allowing users to create public/private/password-protected groups, manage members, and control group operations. ---- - ## Prerequisites -- React v18.2.0+ -- CometChat React UI Kit v6.1.0+ -- CometChat Chat SDK JavaScript v4.0.13+ -- Project setup with initialized CometChat credentials (App ID, Auth Key, Region) -- TypeScript support (recommended) -- Basic chat functionality already implemented -- User authentication already configured +See [Prerequisites](/ui-kit/react/guide-overview#prerequisites). Additional requirements: ---- +- TypeScript support (recommended) +- Basic chat functionality already implemented +- User authentication already configured ## Components @@ -40,8 +43,6 @@ Groups Management provides a complete set of features for creating, managing, an | **CometChatBannedMembers** | Manages banned members and unban operations | | **CometChatTransferOwnership** | Transfers group ownership to other members | ---- - ## Integration Steps ### 1. Create Group Implementation @@ -71,8 +72,6 @@ export const CometChatCreateGroup = ({ setShowCreateGroup, onGroupCreated }: Cre }; ``` ---- - ### 2. Join Group Implementation _File: [CometChatJoinGroup.tsx](https://github.com/cometchat/cometchat-uikit-react/blob/v6/sample-app/src/components/CometChatJoinGroup/CometChatJoinGroup.tsx)_ @@ -98,8 +97,6 @@ export const CometChatJoinGroup = ({ group, onHide, onProtectedGroupJoin }) => { }; ``` ---- - ### 3. View Group Members Implementation _File: [CometChatHome.tsx](https://github.com/cometchat/cometchat-uikit-react/blob/v6/sample-app/src/components/CometChatHome/CometChatHome.tsx)_ @@ -127,8 +124,6 @@ const GroupMembersView = ({ group }: { group: CometChat.Group }) => { }; ``` ---- - ### 4. Add Members to Group Implementation _File: [CometChatAddMembers.tsx](https://github.com/cometchat/cometchat-uikit-react/blob/v6/sample-app/src/components/CometChatAddMembers/CometChatAddMembers.tsx)_ @@ -159,8 +154,6 @@ export const CometChatAddMembers = ({ group, onBack }: IAddMembersProps) => { }; ``` ---- - ### 5. Ban Member from Group Implementation _File: [CometChatBannedMembers.tsx](https://github.com/cometchat/cometchat-uikit-react/blob/v6/sample-app/src/components/CometChatBannedMembers/CometChatBannedMembers.tsx)_ @@ -189,8 +182,6 @@ export const CometChatBannedMembers = ({ group }: bannedMembersProp) => { }; ``` ---- - ### 6. Change Member Scope Implementation _File: [CometChatHome.tsx](https://github.com/cometchat/cometchat-uikit-react/blob/v6/sample-app/src/components/CometChatHome/CometChatHome.tsx)_ @@ -215,8 +206,6 @@ const changeMemberScope = async (member: CometChat.GroupMember, newScope: string }; ``` ---- - ### 7. Transfer Group Ownership Implementation _File: [CometChatTransferOwnership.tsx](https://github.com/cometchat/cometchat-uikit-react/blob/v6/sample-app/src/components/CometChatTransferOwnership/CometChatTransferOwnership.tsx)_ @@ -250,8 +239,6 @@ export const CometChatTransferOwnership = ({ group, onClose }: ITransferOwnershi }; ``` ---- - ## Implementation Flow - **Fetch Data / Group Information**: Retrieve group details and member lists. @@ -259,8 +246,6 @@ export const CometChatTransferOwnership = ({ group, onClose }: ITransferOwnershi - **Execute Group Operations / Action Handlers**: Handle creation, adding, banning, etc., with proper error handling. - **Live Updates / Event Handling**: Subscribe to CometChatGroupEvents for member changes and update UI in real time. ---- - ## Customization Options - Styling: Override CSS classes @@ -271,8 +256,6 @@ export const CometChatTransferOwnership = ({ group, onClose }: ITransferOwnershi - Event Handling: Custom responses - Search & Filtering: Add search for members ---- - ## Filtering / Edge Cases - Handle group type restrictions, member limits, and permission checks @@ -280,8 +263,6 @@ export const CometChatTransferOwnership = ({ group, onClose }: ITransferOwnershi - Handle empty groups and network errors gracefully - Maintain UI consistency with concurrent actions ---- - ## Error Handling & Permission Management ```tsx @@ -309,8 +290,6 @@ const handleGroupOperation = async (operation: () => Promise) => { }; ``` ---- - ## Context-Specific Notes - Different handling for public, private, password-protected groups @@ -319,8 +298,6 @@ const handleGroupOperation = async (operation: () => Promise) => { - Real-time updates across devices - Works cross-platform ---- - ## Summary / Feature Matrix | Feature | Component / Method | File Reference | @@ -335,13 +312,19 @@ const handleGroupOperation = async (operation: () => Promise) => { | Group events | `CometChatGroupEvents` | [CometChatHome.tsx](https://github.com/cometchat/cometchat-uikit-react/blob/v6/sample-app/src/components/CometChatHome/CometChatHome.tsx), [CometChatAddMembers.tsx](https://github.com/cometchat/cometchat-uikit-react/blob/v6/sample-app/src/components/CometChatAddMembers/CometChatAddMembers.tsx), [CometChatBannedMembers.tsx](https://github.com/cometchat/cometchat-uikit-react/blob/v6/sample-app/src/components/CometChatBannedMembers/CometChatBannedMembers.tsx), [CometChatTransferOwnership.tsx](https://github.com/cometchat/cometchat-uikit-react/blob/v6/sample-app/src/components/CometChatTransferOwnership/CometChatTransferOwnership.tsx) | | Member management | `CometChat.GroupMembersRequestBuilder` | [CometChatHome.tsx](https://github.com/cometchat/cometchat-uikit-react/blob/v6/sample-app/src/components/CometChatHome/CometChatHome.tsx), [CometChatTransferOwnership.tsx](https://github.com/cometchat/cometchat-uikit-react/blob/v6/sample-app/src/components/CometChatTransferOwnership/CometChatTransferOwnership.tsx) | ---- - -## Next Steps & Further Reading - -- [CometChat React UI Kit Documentation](https://www.cometchat.com/docs/ui-kit/react/overview) -- [Sample App Repository](https://github.com/cometchat/cometchat-uikit-react/tree/v6/sample-app) -- Group Management Features -- Advanced Customization Guide -- Member Management Documentation - +## Next Steps + + + + Display and manage group lists. + + + Display and manage group member lists. + + + Browse all feature and formatter guides. + + + Full working sample application on GitHub. + + diff --git a/ui-kit/react/guide-message-privately.mdx b/ui-kit/react/guide-message-privately.mdx index 1d0add7ad..491d64c70 100644 --- a/ui-kit/react/guide-message-privately.mdx +++ b/ui-kit/react/guide-message-privately.mdx @@ -1,8 +1,19 @@ --- title: "Message Privately" sidebarTitle: "Message Privately" +description: "Launch a direct 1:1 chat from a group member profile in CometChat React UI Kit." --- + +- **Package:** `@cometchat/chat-uikit-react` +- **Key components:** `CometChatMessages`, `CometChatGroupMembers`, `CometChatMessageComposer`, `CometChatMessageList`, `CometChatMessageHeader` +- **Required setup:** `CometChatUIKit.init(UIKitSettings)` then `CometChatUIKit.login("UID")` +- **Purpose:** Launch a direct 1:1 chat from a group member profile +- **Sample app:** [GitHub](https://github.com/cometchat/cometchat-uikit-react/tree/v6/sample-app) +- **Related:** [All Guides](/ui-kit/react/guide-overview) + + + Enable users to initiate private conversations with group members directly from group chat interfaces. ## Overview @@ -11,18 +22,16 @@ The Message Privately (from a Group) feature allows users to start private, one- - Allows users to start private conversations with specific group members directly from a group. - Enables confidential discussions, sharing sensitive information, or asking personal questions without disrupting the group conversation. -- Your app will support initiating private messages from group contexts, allowing users to seamlessly switch between group discussions and private conversations. +- Your app will support initiating private messages from group contexts, allowing users to smoothly switch between group discussions and private conversations. --- ## Prerequisites -- React v18.2.0+ -- CometChat React UI Kit v6.1.0+ -- CometChat Chat SDK JavaScript v4.0.13+ -- Project setup with initialized CometChat credentials (App ID, Auth Key, Region) -- TypeScript support (recommended) -- Group chat functionality already implemented +See [Prerequisites](/ui-kit/react/guide-overview#prerequisites). Additional requirements: + +- TypeScript support (recommended) +- Group chat functionality already implemented - User management and conversation handling already implemented --- @@ -316,10 +325,21 @@ const startPrivateChatFromGroup = async (user: CometChat.User, group: CometChat. --- -## Next Steps & Further Reading - -- [CometChat React UI Kit Documentation](https://www.cometchat.com/docs/ui-kit/react/overview) -- [Sample App Repository](https://github.com/cometchat/cometchat-uikit-react/tree/v6/sample-app) -- Group Management Features -- User Management Features -- Message Types & Features +## Next Steps + + + + Display and manage group member lists. + + + Render real-time message threads. + + + Browse all feature and formatter guides. + + + Full working sample application on GitHub. + + + +*** diff --git a/ui-kit/react/guide-new-chat.mdx b/ui-kit/react/guide-new-chat.mdx index 54ee2e6b2..d0c7e641b 100644 --- a/ui-kit/react/guide-new-chat.mdx +++ b/ui-kit/react/guide-new-chat.mdx @@ -1,13 +1,24 @@ --- title: "New Chat" sidebarTitle: "New Chat" +description: "Build a unified new chat entry point for starting 1:1 or group conversations in CometChat React UI Kit." --- + +- **Package:** `@cometchat/chat-uikit-react` +- **Key components:** `CometChatUsers`, `CometChatGroups`, `CometChatJoinGroup`, `CometChatSelector` +- **Required setup:** `CometChatUIKit.init(UIKitSettings)` then `CometChatUIKit.login("UID")` +- **Purpose:** Unified new chat entry point for starting 1:1 or group conversations +- **Sample app:** [GitHub](https://github.com/cometchat/cometchat-uikit-react/tree/v6/sample-app) +- **Related:** [All Guides](/ui-kit/react/guide-overview) + + + Enable users to create new conversations with individual users or join existing groups in your React chat app. ## Overview -The New Chat feature allows users to initiate conversations with other users or join group conversations, providing a seamless way to start new communications. +The New Chat feature allows users to initiate conversations with other users or join group conversations, providing a smooth way to start new communications. - Allows users to initiate conversations with other users or join group conversations. - Enables users to expand their network, join group discussions, and create new chat threads without navigating through complex menus. @@ -17,12 +28,10 @@ The New Chat feature allows users to initiate conversations with other users or ## Prerequisites -- React v18.2.0+ -- CometChat React UI Kit v6.1.0+ -- CometChat Chat SDK JavaScript v4.0.13+ -- Project setup with initialized CometChat credentials (App ID, Auth Key, Region) -- TypeScript support (recommended) -- User authentication and basic chat functionality implemented +See [Prerequisites](/ui-kit/react/guide-overview#prerequisites). Additional requirements: + +- TypeScript support (recommended) +- User authentication and basic chat functionality implemented - User and group management components available --- @@ -257,9 +266,21 @@ const joinGroup = (e) => { --- -## Next Steps & Further Reading - -- [CometChat React UI Kit Documentation](https://www.cometchat.com/docs/ui-kit/react/overview) -- [Sample App Repository](https://github.com/cometchat/cometchat-uikit-react/tree/v6/sample-app) -- User Management Features -- Group Management Features +## Next Steps + + + + Display and manage conversation lists. + + + Display and manage group lists. + + + Browse all feature and formatter guides. + + + Full working sample application on GitHub. + + + +*** diff --git a/ui-kit/react/guide-overview.mdx b/ui-kit/react/guide-overview.mdx index 10ab044fd..ec150afd3 100644 --- a/ui-kit/react/guide-overview.mdx +++ b/ui-kit/react/guide-overview.mdx @@ -1,13 +1,31 @@ --- title: "Overview" sidebarTitle: "Overview" +description: "Index of task-oriented feature guides for the CometChat React UI Kit." --- + + +- **Package:** `@cometchat/chat-uikit-react` +- **Purpose:** Index of task-oriented feature guides for the React UI Kit +- **Sample app:** [GitHub](https://github.com/cometchat/cometchat-uikit-react/tree/v6/sample-app) +- **Components:** [Components Overview](/ui-kit/react/components-overview) +- **Guides:** [Block/Unblock](/ui-kit/react/guide-block-unblock-user) | [Call Log Details](/ui-kit/react/guide-call-log-details) | [Group Chat](/ui-kit/react/guide-group-chat) | [Message Privately](/ui-kit/react/guide-message-privately) | [New Chat](/ui-kit/react/guide-new-chat) | [Search Messages](/ui-kit/react/guide-search-messages) | [Threaded Messages](/ui-kit/react/guide-threaded-messages) + + > This page indexes focused, task‑oriented feature guides for the React UI Kit. Each guide shows how to implement a specific capability end‑to‑end using UI components. ## When to Use These Guides Use these guides after completing the base [Getting Started](/ui-kit/react/react-js-integration) (or framework variant: [Next.js](/ui-kit/react/next-js-integration), [React Router](/ui-kit/react/react-router-integration)). They help you layer additional UX without rewriting core chat flows. +## Prerequisites + +- React v18.2.0+ +- CometChat React UI Kit v6.1.0+ +- CometChat Chat SDK JavaScript v4.0.13+ +- CometChat credentials configured (App ID, Auth Key, Region) +- Base integration complete ([React.js](/ui-kit/react/react-js-integration), [Next.js](/ui-kit/react/next-js-integration), or [React Router](/ui-kit/react/react-router-integration)) + ## Guide Directory | Guide | Description | @@ -26,3 +44,21 @@ Use these guides after completing the base [Getting Started](/ui-kit/react/react Need another guide? Open a request via our [Developer Community](http://community.cometchat.com/) or Support. +--- + +## Next Steps + + + + Set up the React UI Kit + + + Explore all UI components + + + Customize themes and styling + + + Handle UI Kit events + + diff --git a/ui-kit/react/guide-search-messages.mdx b/ui-kit/react/guide-search-messages.mdx index 072126f4f..76e677a70 100644 --- a/ui-kit/react/guide-search-messages.mdx +++ b/ui-kit/react/guide-search-messages.mdx @@ -1,8 +1,19 @@ --- title: "Search Messages" sidebarTitle: "Search Messages" +description: "Add full-text message search across conversations with result routing in CometChat React UI Kit." --- + +- **Package:** `@cometchat/chat-uikit-react` +- **Key components:** `CometChatSearchMessages`, `CometChatMessageList`, `CometChatMessageComposer`, `CometChatMessageHeader` +- **Required setup:** `CometChatUIKit.init(UIKitSettings)` then `CometChatUIKit.login("UID")` +- **Purpose:** Full-text message search across conversations with result routing and navigation +- **Sample app:** [GitHub](https://github.com/cometchat/cometchat-uikit-react/tree/v6/sample-app) +- **Related:** [All Guides](/ui-kit/react/guide-overview) + + + Enable users to search messages within conversations and group chats using CometChat's React UI Kit. ## Overview @@ -17,11 +28,9 @@ The Search Messages feature allows users to quickly locate specific messages acr ## Prerequisites -- React v18.2.0+ -- CometChat React UI Kit v6.1.0+ -- CometChat Chat SDK JavaScript v4.0.13+ -- Project setup with initialized CometChat credentials (App ID, Auth Key, Region) -- TypeScript support (recommended) +See [Prerequisites](/ui-kit/react/guide-overview#prerequisites). Additional requirements: + +- TypeScript support (recommended) - Basic messaging functionality already implemented --- @@ -178,9 +187,21 @@ try { --- -## Next Steps & Further Reading - -- [CometChat React UI Kit Documentation](https://www.cometchat.com/docs/ui-kit/react/overview) -- [Sample App Repository](https://github.com/cometchat/cometchat-uikit-react/tree/v6/sample-app) -- Message Management Features -- Advanced Search Features +## Next Steps + + + + The search component reference. + + + Render real-time message threads. + + + Browse all feature and formatter guides. + + + Full working sample application on GitHub. + + + +*** diff --git a/ui-kit/react/guide-threaded-messages.mdx b/ui-kit/react/guide-threaded-messages.mdx index 50c06c07f..a228edef8 100644 --- a/ui-kit/react/guide-threaded-messages.mdx +++ b/ui-kit/react/guide-threaded-messages.mdx @@ -1,8 +1,20 @@ --- title: "Threaded Messages" sidebarTitle: "Threaded Messages" +description: "Implement threaded message replies with parent context, reply list, and focused thread composer in CometChat React UI Kit." --- + +- **Package:** `@cometchat/chat-uikit-react` +- **Key components:** `CometChatThreadedMessages`, `CometChatThreadHeader`, `CometChatMessageList`, `CometChatMessageComposer` +- **Required setup:** `CometChatUIKit.init(UIKitSettings)` then `CometChatUIKit.login("UID")` +- **Purpose:** Threaded message replies with parent context, reply list, and focused thread composer +- **Entry point:** `CometChatMessages.onThreadRepliesClick` opens thread view from group messages +- **Sample app:** [GitHub](https://github.com/cometchat/cometchat-uikit-react/tree/v6/sample-app) +- **Related:** [All Guides](/ui-kit/react/guide-overview) + + + Enable organized threaded conversations within group chats using CometChat's React UI Kit. ## Overview @@ -17,10 +29,8 @@ Threaded messages in group chat allow users to create organized sub-conversation ## Prerequisites -- React v18.2.0+ -- CometChat React UI Kit v6.1.0+ -- CometChat Chat SDK JavaScript v4.0.13+ -- CometChat credentials configured (App ID, Auth Key, Region) +See [Prerequisites](/ui-kit/react/guide-overview#prerequisites). Additional requirements: + - Group chat functionality implemented --- @@ -211,5 +221,19 @@ useEffect(() => { ## Next Steps -- Explore [CometChat React UI Kit Docs](https://www.cometchat.com/docs/ui-kit/react/overview) -- Check the [Sample App Repo](https://github.com/cometchat/cometchat-uikit-react/tree/v6/sample-app) + + + Render real-time message threads. + + + Customize the thread header component. + + + Browse all feature and formatter guides. + + + Full working sample application on GitHub. + + + +*** diff --git a/ui-kit/react/incoming-call.mdx b/ui-kit/react/incoming-call.mdx index e55f9f37f..2e4bea132 100644 --- a/ui-kit/react/incoming-call.mdx +++ b/ui-kit/react/incoming-call.mdx @@ -1,947 +1,500 @@ --- title: "Incoming Call" +description: "Visual notification for incoming voice/video calls with accept and decline controls." --- + +```json +{ + "component": "CometChatIncomingCall", + "package": "@cometchat/chat-uikit-react", + "import": "import { CometChatIncomingCall } from \"@cometchat/chat-uikit-react\";", + "cssImport": "import \"@cometchat/chat-uikit-react/css-variables.css\";", + "description": "Visual notification for incoming voice/video calls with accept and decline controls.", + "cssRootClass": ".cometchat-incoming-call", + "props": { + "data": { + "call": { "type": "any", "default": "auto-detected" }, + "callSettingsBuilder": { "type": "(call: CometChat.Call) => CallSettingsBuilder", "default": "undefined" } + }, + "callbacks": { + "onAccept": "(call: CometChat.Call) => void", + "onDecline": "(call: CometChat.Call) => void", + "onError": "((error: CometChat.CometChatException) => void) | null" + }, + "sound": { + "disableSoundForCalls": { "type": "boolean", "default": false }, + "customSoundForCalls": { "type": "string", "default": "undefined" } + }, + "viewSlots": { + "itemView": "(call: CometChat.Call) => JSX.Element", + "leadingView": "(call: CometChat.Call) => JSX.Element", + "titleView": "(call: CometChat.Call) => JSX.Element", + "subtitleView": "(call: CometChat.Call) => JSX.Element", + "trailingView": "(call: CometChat.Call) => JSX.Element" + } + }, + "events": [ + { "name": "CometChatCallEvents.ccCallRejected", "payload": "CometChat.Call" }, + { "name": "CometChatCallEvents.ccCallAccepted", "payload": "CometChat.Call" }, + { "name": "CometChatCallEvents.ccCallEnded", "payload": "CometChat.Call" } + ] +} +``` + -## Overview - -The `Incoming call` is a Component that serves as a visual representation when the user receives an incoming call, such as a voice call or video call, providing options to answer or decline the call. - - - - - -The `Incoming Call` is comprised of the following base components: - -| Components | Description | -| ------------------- | ---------------------------------------------------------------------------------------------------------------------------------------------- | -| cometchat-list-item | This component’s view consists of avatar, status indicator , title, and subtitle. The fields are then mapped with the SDK’s user, group class. | -| cometchat-button | This component represents a button with optional icon and text. | -| cometchat-avatar | This component component displays an image or user's avatar with fallback to the first two letters of the username. | - -## Usage +## Where It Fits -### Integration +`CometChatIncomingCall` is an overlay component that auto-detects incoming calls and renders a notification with accept/decline buttons. Place it at the app root level so it appears above all other content. - - ```tsx import { CometChatIncomingCall } from "@cometchat/chat-uikit-react"; -import React from "react"; +import "@cometchat/chat-uikit-react/css-variables.css"; -const IncomingCallsDemo = () => { - return ; -}; - -export default IncomingCallsDemo; -``` - - - - -```tsx -import { IncomingCallsDemo } from "./IncomingCallsDemo"; - -export default function App() { +function App() { return ( -
-
- -
+
+ + {/* rest of app */}
); } ``` - - - - -### Actions - -[Actions](/ui-kit/react/components-overview#actions) dictate how a component functions. They are divided into two types: Predefined and User-defined. You can override either type, allowing you to tailor the behavior of the component to fit your specific needs. - -##### 1. onAccept - -`onAccept` is triggered when you click the accept button of the `Incoming Call` component. You can override this action using the following code snippet. - - - -```ts -import { CometChatIncomingCall } from "@cometchat/chat-uikit-react"; -import React from "react"; - -const IncomingCallsDemo = () => { - const handleOnAccept = () => { - console.log("custom on accept action"); - }; - - return ; -}; + + + -export default IncomingCallsDemo; -``` +--- - +## Minimal Render - -```js +```tsx import { CometChatIncomingCall } from "@cometchat/chat-uikit-react"; -import React from "react"; - -const IncomingCallsDemo = () => { - const handleOnAccept = () => { - console.log("custom on accept action"); - }; +import "@cometchat/chat-uikit-react/css-variables.css"; - return ; -}; +function IncomingCallDemo() { + return ; +} -export default IncomingCallsDemo; +export default IncomingCallDemo; ``` - - - - -##### 2. onDecline +Root CSS class: `.cometchat-incoming-call` -`onDecline` is triggered when you click the Decline button of the `Incoming Call` component. You can override this action using the following code snippet. +--- - - -```ts -import { CometChatIncomingCall } from "@cometchat/chat-uikit-react"; -import React from "react"; +## Actions and Events -const IncomingCallsDemo = () => { - const handleOnDecline = () => { - console.log("your custom on decline action"); - }; +### Callback Props - return ; -}; +#### onAccept -export default IncomingCallsDemo; -``` +Fires when the accept button is clicked. - - - -```js +```tsx import { CometChatIncomingCall } from "@cometchat/chat-uikit-react"; -import React from "react"; - -const IncomingCallsDemo = () => { - const handleOnDecline = () => { - console.log("your custom on decline action"); - }; - - return ; -}; +import { CometChat } from "@cometchat/chat-sdk-javascript"; -export default IncomingCallsDemo; +function IncomingCallWithAccept() { + return ( + { + console.log("Call accepted:", call); + }} + /> + ); +} ``` - - - - -##### 3. onError - -This action doesn't change the behavior of the component but rather listens for any errors that occur in the Incoming Call component. - - - -```ts -import { CometChatIncomingCall } from "@cometchat/chat-uikit-react"; -import React from "react"; - -const IncomingCallsDemo = () => { - const handleOnError = (error: CometChat.CometChatException) => { - console.log("your custom on error action", error); - }; - - return ; -}; +#### onDecline -export default IncomingCallsDemo; -``` +Fires when the decline button is clicked. - - - -```js +```tsx import { CometChatIncomingCall } from "@cometchat/chat-uikit-react"; -import React from "react"; - -const IncomingCallsDemo = () => { - const handleOnError = (error) => { - console.log("your custom on error action", error); - }; - - return ; -}; +import { CometChat } from "@cometchat/chat-sdk-javascript"; -export default IncomingCallsDemo; +function IncomingCallWithDecline() { + return ( + { + console.log("Call declined:", call); + }} + /> + ); +} ``` - - - - -*** - -### Filters - -You can set `CallSettingsBuilder` in the Incoming Call Component to customise the calling experience. To know more about the filters available please refer to [CallSettingsBuilder](/sdk/javascript/direct-call#settings). - - - -```ts -import { CometChatIncomingCall } from "@cometchat/chat-uikit-react"; -import React from "react"; - -const IncomingCallsDemo = () => { - const getCallSettingsBuilder = (call: CometChat.Call) => { - return new CometChatCalls.CallSettingsBuilder() - .setIsAudioOnlyCall( - call?.getType() === CometChatUIKitConstants.MessageTypes.audio - ? true - : false - ) - .build(); - }; - - return ; -}; - -export default IncomingCallsDemo; -``` +#### onError - +Fires on internal errors. - -```js +```tsx import { CometChatIncomingCall } from "@cometchat/chat-uikit-react"; -import React from "react"; - -const IncomingCallsDemo = () => { - const getCallSettingsBuilder = (call) => { - return new CometChatCalls.CallSettingsBuilder() - .setIsAudioOnlyCall( - call?.getType() === CometChatUIKitConstants.MessageTypes.audio - ? true - : false - ) - .build(); - }; - - return ; -}; - -export default IncomingCallsDemo; -``` - - - - - -### Events - -[Events](/ui-kit/react/components-overview#events) are emitted by a `Component`. By using event you can extend existing functionality. Being global events, they can be applied in Multiple Locations and are capable of being Added or Removed. - -The list of events emitted by the Incoming Call component is as follows. - -| Event | Description | -| ------------------ | ---------------------------------------------------------------------------- | -| **ccCallRejected** | This event is triggered when the initiated call is rejected by the receiver. | -| **ccCallAccepted** | This event is triggered when the initiated call is accepted by the receiver. | -| **ccCallEnded** | This event is triggered when the initiated call successfully ends. | +import { CometChat } from "@cometchat/chat-sdk-javascript"; - - -```tsx -const ccCallRejected = CometChatCallEvents.ccCallRejected.subscribe( - (call: CometChat.Call) => { - //Your Code - } -); - -const ccCallAccepted = CometChatCallEvents.ccCallAccepted.subscribe( - (call: CometChat.Call) => { - //Your Code - } -); - -const ccCallEnded = CometChatCallEvents.ccCallEnded.subscribe( - (call: CometChat.Call) => { - //Your Code - } -); +function IncomingCallWithError() { + return ( + { + console.error("IncomingCall error:", error); + }} + /> + ); +} ``` - +### Global UI Events - +`CometChatCallEvents` emits events subscribable from anywhere in the application. -*** +| Event | Fires when | Payload | +| --- | --- | --- | +| `ccCallRejected` | Incoming call is rejected | `CometChat.Call` | +| `ccCallAccepted` | Incoming call is accepted | `CometChat.Call` | +| `ccCallEnded` | Call ends | `CometChat.Call` | - - ```tsx -ccCallRejected?.unsubscribe(); - -ccCallAccepted?.unsubscribe(); +import { useEffect } from "react"; +import { CometChatCallEvents } from "@cometchat/chat-uikit-react"; +import { CometChat } from "@cometchat/chat-sdk-javascript"; -ccCallEnded?.unsubscribe(); +function useCallEvents() { + useEffect(() => { + const acceptedSub = CometChatCallEvents.ccCallAccepted.subscribe( + (call: CometChat.Call) => console.log("Accepted:", call) + ); + const rejectedSub = CometChatCallEvents.ccCallRejected.subscribe( + (call: CometChat.Call) => console.log("Rejected:", call) + ); + + return () => { + acceptedSub?.unsubscribe(); + rejectedSub?.unsubscribe(); + }; + }, []); +} ``` - - - +### SDK Events (Real-Time, Automatic) -*** +The component listens to SDK call events internally for real-time incoming call detection. No manual attachment needed. -## Customization +--- -To fit your app's design requirements, you can customize the appearance of the Incoming Call component. We provide exposed methods that allow you to modify the experience and behavior according to your specific needs. +## Custom View Slots -### Style +View slots for `CometChatIncomingCall` are functions that receive the `CometChat.Call` object. -Using CSS you can customize the look and feel of the component in your app like the color, size, shape, and fonts. +| Slot | Signature | Replaces | +| --- | --- | --- | +| `itemView` | `(call: CometChat.Call) => JSX.Element` | Entire list item | +| `leadingView` | `(call: CometChat.Call) => JSX.Element` | Avatar / left section | +| `titleView` | `(call: CometChat.Call) => JSX.Element` | Name / title text | +| `subtitleView` | `(call: CometChat.Call) => JSX.Element` | Subtitle text | +| `trailingView` | `(call: CometChat.Call) => JSX.Element` | Right section | -**Example:** +### leadingView - + - - -```ts -import { CometChatIncomingCall } from "@cometchat/chat-uikit-react"; -import React from "react"; - -const IncomingCallsDemo = () => { - return ; -}; - -export default IncomingCallsDemo; -``` - - - - -```js -import { CometChatIncomingCall } from "@cometchat/chat-uikit-react"; -import React from "react"; - -const IncomingCallsDemo = () => { - return ; -}; - -export default IncomingCallsDemo; -``` - - - - -```css -.cometchat-incoming-call { - display: flex; - width: 555px; - padding: 30.833px; - flex-direction: column; - align-items: center; - gap: 24.667px; - flex-shrink: 0; - border-radius: 18.5px; - border: 1.542px solid #aa9ee8; - background: #fff; - box-shadow: 0px 18.5px 24.667px -6.167px rgba(16, 24, 40, 0.08), 0px 6.167px - 9.25px -3.083px rgba(16, 24, 40, 0.03); -} - -.cometchat-incoming-call .cometchat-list-item { - width: 100%; -} - -.cometchat-incoming-call .cometchat-incoming-call__button-group { - justify-content: center; -} - -.cometchat-incoming-call__button-decline, -.cometchat-incoming-call__button-accept { - background-color: white; - border-radius: 12px; - border: 1.5px solid #dcdcdc; -} - -.cometchat-incoming-call__button-decline .cometchat-button:hover, -.cometchat-incoming-call__button-decline .cometchat-button { - background-color: white; - background-color: white; - border-radius: 12px; - border: 1.5px solid #dcdcdc; -} - -.cometchat-incoming-call__button-accept .cometchat-button:hover, -.cometchat-incoming-call__button-accept .cometchat-button { - background-color: #6852d6; - color: white; -} - -.cometchat-incoming-call__button-decline .cometchat-button__text { - color: #f44649; - font: 500 21px/120% roboto; - font-style: normal; -} - -.cometchat-incoming-call__button-accept .cometchat-button__text { - color: #fff; - font: 500 21px/120% roboto; - font-style: normal; -} - -.cometchat-incoming-call__button-decline .cometchat .cometchat-button::before, -.cometchat-incoming-call__button-accept .cometchat .cometchat-button::before { - content: url("../assets/call-decline.svg"); - width: 37px; - height: 37px; - flex-shrink: 0; -} - -.cometchat-incoming-call__button-accept .cometchat .cometchat-button::before { - content: url("../assets/call-accept.svg"); -} - -.cometchat-incoming-call__avatar, -.cometchat-incoming-call__avatar .cometchat-avatar { - display: flex; - width: 123.333px; - height: 123.333px; - justify-content: center; - align-items: center; - border-radius: 24.667px; - background: #aa9ee8; -} - -.cometchat-incoming-call__avatar .cometchat-avatar__image { - border-radius: 24.667px; -} - -.cometchat-incoming-call__avatar .cometchat-avatar__text { - color: #fff; - text-align: center; - font: 500 21px/120% roboto; - font-style: normal; -} - -.cometchat-incoming-call .cometchat-list-item__body { - flex-direction: column-reverse; - gap: 20px; - background: #fff; -} - -.cometchat-incoming-call .cometchat-list-item__body-title { - color: #141414; -} - -.cometchat-incoming-call .cometchat-list-item__title-container { - text-align: center; - gap: 6px; -} +```tsx +import { CometChat } from "@cometchat/chat-sdk-javascript"; +import { CometChatAvatar, CometChatIncomingCall } from "@cometchat/chat-uikit-react"; -.cometchat-list-item__body-subtitle { - justify-content: center; +function CustomLeadingIncoming() { + return ( + ( + + )} + /> + ); } ``` - - - +### titleView -### Functionality - -These are a set of small functional customizations that allow you to fine-tune the overall experience of the component. With these, you can change text, set custom icons, and toggle the visibility of UI elements. - -Here is a code snippet demonstrating how you can customize the functionality of the `Incoming Call` component. + + + - - -```ts +```tsx +import { CometChat } from "@cometchat/chat-sdk-javascript"; import { CometChatIncomingCall } from "@cometchat/chat-uikit-react"; -import React from "react"; -const IncomingCallsDemo = () => { +function CustomTitleIncoming() { return ( ( +
{call.getCallInitiator()?.getName()}
+ )} /> ); -}; - -export default IncomingCallsDemo; +} ``` -
+### itemView - -```js -import { CometChatIncomingCall } from "@cometchat/chat-uikit-react"; -import React from "react"; + + + -const IncomingCallsDemo = () => { +```tsx +import { CometChat } from "@cometchat/chat-sdk-javascript"; +import { CometChatAvatar, CometChatIncomingCall } from "@cometchat/chat-uikit-react"; + +function CustomItemViewIncoming() { return ( ( +
+ +
{call.getCallInitiator()?.getName()}
+
{"Incoming " + call.getType() + " call"}
+
+ )} /> ); -}; - -export default IncomingCallsDemo; +} ``` -
- -
- -Below is a list of customizations along with corresponding code snippets - -| Property | Description | Code | -| ----------------- | ------------------------------------------------------------------------------------- | --------------------------------------------------- | -| **Call** | The CometChat call object used to initialize and display the incoming call component. | `call={callObject}` | -| **Disable sound** | Disables the sound for incoming calls. | `disableSoundForCalls={true}` | -| **Custom sound** | Specifies a custom sound to play for incoming calls. | `customSoundForCalls='Your Custom Sound For Calls'` | - -*** - -### Advanced - -For advanced-level customization, you can set custom views to the component. This lets you tailor each aspect of the component to fit your exact needs and application aesthetics. You can create and define your views, layouts, and UI elements and then incorporate those into the component. - -*** +--- -#### SubtitleView +## Common Patterns -Property `subtitleView` is a function that renders a JSX element to display the subtitle view. +### Disable ringtone - - -```ts -import { CometChat } from "@cometchat/chat-sdk-javascript"; +```tsx import { CometChatIncomingCall } from "@cometchat/chat-uikit-react"; -import React from "react"; - -const IncomingCallsDemo = () => { - const getSubtitleView = (call: CometChat.Call): JSX.Element => { - /** Return custom subtitle view */ - }; - - return ; -}; -export default IncomingCallsDemo; +function SilentIncoming() { + return ; +} ``` - +### Custom ringtone - -```js -import { CometChat } from "@cometchat/chat-sdk-javascript"; +```tsx import { CometChatIncomingCall } from "@cometchat/chat-uikit-react"; -import React from "react"; - -const IncomingCallsDemo = () => { - const getSubtitleView = (call) => { - /** Return custom subtitle view */ - }; - - return ; -}; -export default IncomingCallsDemo; +function CustomSoundIncoming() { + return ; +} ``` - +--- - +## CSS Architecture -#### LeadingView +### Key Selectors -Property `leadingView` is a function that renders a JSX element to display the leading view. +| Target | Selector | +| --- | --- | +| Root | `.cometchat-incoming-call` | +| List item | `.cometchat-incoming-call .cometchat-list-item` | +| Body title | `.cometchat-incoming-call .cometchat-list-item__body-title` | +| Button group | `.cometchat-incoming-call__button-group` | +| Decline button | `.cometchat-incoming-call__button-decline` | +| Accept button | `.cometchat-incoming-call__button-accept` | -The customized call interface is displayed below. +### Example: Brand-themed incoming call - + -Use the following code to achieve the customization shown above. - - - -```ts -import { CometChat } from "@cometchat/chat-sdk-javascript"; -import { CometChatAvatar, CometChatIncomingCall } from "@cometchat/chat-uikit-react"; -import React from "react"; - -const IncomingCallsDemo = () => { - const getLeadingView = (call: CometChat.Call) => { - return ( -
- -
- ) - }; +```css +.cometchat-incoming-call { + border-radius: 18.5px; + border: 1.542px solid #aa9ee8; + background: #fff; +} - return ; -}; +.cometchat-incoming-call__button-decline .cometchat-button__text { + color: #f44649; +} -export default IncomingCallsDemo; +.cometchat-incoming-call__button-accept .cometchat-button { + background-color: #6852d6; +} ``` -
- - -```js -import { CometChat } from "@cometchat/chat-sdk-javascript"; -import { CometChatAvatar, CometChatIncomingCall } from "@cometchat/chat-uikit-react"; -import React from "react"; - -const IncomingCallsDemo = () => { - const getLeadingView = (call) => { - return ( -
- -
- ) - }; - - return ; -}; +--- -export default IncomingCallsDemo; -``` +## Accessibility -
+The accept and decline buttons are keyboard-focusable and activate on Enter/Space. The caller name and call type are exposed as text content. The component renders as an absolutely positioned overlay. - -```css -.cometchat-incoming-call__avatar { - display: none; -} -``` +--- - +--- -
+## Props -#### TitleView +All props are optional. -Property `titleView` is a function that renders a JSX element to display the title view. +--- -The customized call interface is displayed below. +### call - - - +Sets a specific call object for the incoming call display. -Use the following code to achieve the customization shown above. +| | | +| --- | --- | +| Type | `any` | +| Default | Auto-detected | - - -```ts -import { CometChat } from "@cometchat/chat-sdk-javascript"; -import { CometChatIncomingCall } from "@cometchat/chat-uikit-react"; -import React from "react"; - -const IncomingCallsDemo = () => { - const getTitleView = (call: CometChat.Call) => { - return ( -
- {call?.getCallInitiator()?.getName()} -
-
- {call.getCallInitiator()?.getRole()} -
-
- ) - }; +--- - return ; -}; +### callSettingsBuilder -export default IncomingCallsDemo; -``` +Custom call settings builder for the call session. - +| | | +| --- | --- | +| Type | `(call: CometChat.Call) => typeof CometChatUIKitCalls.CallSettingsBuilder` | +| Default | `undefined` | - -```js -import { CometChat } from "@cometchat/chat-sdk-javascript"; -import { CometChatIncomingCall } from "@cometchat/chat-uikit-react"; -import React from "react"; - -const IncomingCallsDemo = () => { - const getTitleView = (call) => { - return ( -
- {call?.getCallInitiator()?.getName()} -
-
- {call.getCallInitiator()?.getRole()} -
-
- ) - }; +--- - return ; -}; +### customSoundForCalls -export default IncomingCallsDemo; -``` +Custom sound file URL for incoming calls. - +| | | +| --- | --- | +| Type | `string` | +| Default | `undefined` | - -```css -.incoming-call__title-wrapper { - display: flex; - width: 370px; - height: 37px; - padding: 2px 10px; - align-items: center; - gap: 10px; - color: #141414; - font: 700 24px Roboto; -} +--- -.incoming-call__tag { - display: flex; - height: 30.036px; - padding: 2.002px 6.007px; - justify-content: center; - align-items: center; - gap: 6.007px; - border-radius: 14.017px; - background: #09C26F; - color: #FFF; - font: 600 12px Roboto; -} +### disableSoundForCalls -.incoming-call__tag-icon { - background-image: url(""); - background-size: contain; - height: 20px; - width: 20px; -} -``` +Disables the incoming call ringtone. - +| | | +| --- | --- | +| Type | `boolean` | +| Default | `false` | - +--- -#### TrailingView +### itemView -Property `trailingView` is a function that renders a JSX element to display the trailing view. +Custom renderer for the entire list item. -The customized call interface is displayed below. +| | | +| --- | --- | +| Type | `(call: CometChat.Call) => JSX.Element` | +| Default | `undefined` | - - - +--- -Use the following code to achieve the customization shown above. +### leadingView - - -```ts -import { CometChat } from "@cometchat/chat-sdk-javascript"; -import { CometChatIncomingCall } from "@cometchat/chat-uikit-react"; -import React from "react"; - -const IncomingCallsDemo = () => { - const getTrailingView = (call: CometChat.Call) => { - return ( -
-
- {call.getCallInitiator()?.getRole()} -
- ) - }; +Custom renderer for the avatar / left section. - return ; -}; +| | | +| --- | --- | +| Type | `(call: CometChat.Call) => JSX.Element` | +| Default | `undefined` | -export default IncomingCallsDemo; -``` +--- - +### onAccept - -```js -import { CometChat } from "@cometchat/chat-sdk-javascript"; -import { CometChatIncomingCall } from "@cometchat/chat-uikit-react"; -import React from "react"; - -const IncomingCallsDemo = () => { - const getTrailingView = (call) => { - return ( -
-
- {call.getCallInitiator()?.getRole()} -
- ) - }; +Callback fired when the accept button is clicked. - return ; -}; +| | | +| --- | --- | +| Type | `(call: CometChat.Call) => void` | +| Default | `undefined` | -export default IncomingCallsDemo; -``` - - +--- - -```css -.incoming-call__avatar { - display: flex; - height: 62px; - padding: 1px 3px; - flex-direction: column; - justify-content: center; - align-items: center; - gap: 3px; - border-radius: 7px; - background: #AA9EE8; - color: #FFF; - font: 600 10px Roboto; -} +### onDecline -.incoming-call__avatar-icon { - background-image: url(" +| | | +| --- | --- | +| Type | `(call: CometChat.Call) => void` | +| Default | `undefined` | - +--- -#### ItemView +### onError -Property `itemView` is a function that renders a JSX element to display the item view. +Callback fired when the component encounters an error. -The customized call interface is displayed below. +| | | +| --- | --- | +| Type | `((error: CometChat.CometChatException) => void) \| null` | +| Default | `undefined` | - - - +--- -Use the following code to achieve the customization shown above. +### subtitleView - - -```ts -import { CometChat } from "@cometchat/chat-sdk-javascript"; -import { CometChatAvatar, CometChatIncomingCall } from "@cometchat/chat-uikit-react"; -import React from "react"; - -const IncomingCallsDemo = () => { - const getItemView = (call: CometChat.Call) => { - return ( -
- -
-
- {call?.getCallInitiator()?.getName()} -
-
- {"Incoming " + call.getType() + " call"} -
-
-
- ) - }; +Custom renderer for the subtitle text. - return ; -}; +| | | +| --- | --- | +| Type | `(call: CometChat.Call) => JSX.Element` | +| Default | `undefined` | -export default IncomingCallsDemo; -``` +--- -
+### titleView - -```js -import { CometChat } from "@cometchat/chat-sdk-javascript"; -import { CometChatAvatar, CometChatIncomingCall } from "@cometchat/chat-uikit-react"; -import React from "react"; - -const IncomingCallsDemo = () => { - const getItemView = (call) => { - return ( -
- -
-
- {call?.getCallInitiator()?.getName()} -
-
- {"Incoming " + call.getType() + " call"} -
-
-
- ) - }; +Custom renderer for the name / title text. - return ; -}; +| | | +| --- | --- | +| Type | `(call: CometChat.Call) => JSX.Element` | +| Default | `undefined` | -export default IncomingCallsDemo; -``` +--- -
+### trailingView - -```css -.incoming-call__itemview { - display: flex; - flex-direction: column; - justify-content: center; - align-items: center; - gap: 20px; - align-self: stretch; -} +Custom renderer for the right section. -.incoming-call__itemview .cometchat-avatar, -.incoming-call__itemview .cometchat-avatar__image { - height: 90px; - width: 90px; - border-radius: 24px; -} +| | | +| --- | --- | +| Type | `(call: CometChat.Call) => JSX.Element` | +| Default | `undefined` | -.incoming-call__itemview .cometchat-avatar__text { - color: #FFF; - text-align: center; - font: 700 32px Roboto -} +--- -.incoming-call__itemview-title { - color: #141414; - text-align: center; - font: 700 24px Roboto; -} +## Events -.incoming-call__itemview-subtitle { - color: var(--Color-Text-Color-Text-Secondary, #727272); - font: 400 16px Roboto; -} -``` +| Event | Payload | Fires when | +| --- | --- | --- | +| `CometChatCallEvents.ccCallRejected` | `CometChat.Call` | Call rejected | +| `CometChatCallEvents.ccCallAccepted` | `CometChat.Call` | Call accepted | +| `CometChatCallEvents.ccCallEnded` | `CometChat.Call` | Call ended | - +--- -
+## CSS Selectors + +| Target | Selector | +| --- | --- | +| Root | `.cometchat-incoming-call` | +| List item | `.cometchat-incoming-call .cometchat-list-item` | +| Body title | `.cometchat-incoming-call .cometchat-list-item__body-title` | +| Title container | `.cometchat-incoming-call .cometchat-list-item__title-container` | +| Trailing view | `.cometchat-incoming-call .cometchat-list-item__trailing-view` | +| Button group | `.cometchat-incoming-call__button-group` | +| Decline button | `.cometchat-incoming-call__button-decline` | +| Accept button | `.cometchat-incoming-call__button-accept` | diff --git a/ui-kit/react/link/changelog.mdx b/ui-kit/react/link/changelog.mdx index 8c698a26d..e3acadbd7 100644 --- a/ui-kit/react/link/changelog.mdx +++ b/ui-kit/react/link/changelog.mdx @@ -1,4 +1,4 @@ --- title: "Changelog" url: "https://github.com/cometchat/cometchat-uikit-react/releases?q=v6&expanded=true" ---- \ No newline at end of file +--- diff --git a/ui-kit/react/link/figma.mdx b/ui-kit/react/link/figma.mdx index 172dd3788..784cf16e7 100644 --- a/ui-kit/react/link/figma.mdx +++ b/ui-kit/react/link/figma.mdx @@ -1,4 +1,4 @@ --- title: "Figma Design" url: "https://www.figma.com/community/file/1442863561340379957/cometchat-ui-kit-for-web" ---- \ No newline at end of file +--- diff --git a/ui-kit/react/link/sample.mdx b/ui-kit/react/link/sample.mdx index 3f7e45be6..d7748ae0d 100644 --- a/ui-kit/react/link/sample.mdx +++ b/ui-kit/react/link/sample.mdx @@ -1,4 +1,4 @@ --- title: "React Sample App" url: "https://github.com/cometchat/cometchat-uikit-react/tree/v6/sample-app" ---- \ No newline at end of file +--- diff --git a/ui-kit/react/localize.mdx b/ui-kit/react/localize.mdx index 45f62ad52..103136eaa 100644 --- a/ui-kit/react/localize.mdx +++ b/ui-kit/react/localize.mdx @@ -1,87 +1,79 @@ --- title: "Localization" sidebarTitle: "Localize" +description: "Configure multi-language localization, custom translations, and date/time formatting in CometChat React UI Kit." --- -## **Overview** + -React UI Kit provides **multi-language localization** to **adapt** the UI elements based on the user's preferred language settings. The **CometChatLocalize** class allows developers to: +| Field | Value | +| --- | --- | +| Package | `@cometchat/chat-uikit-react` | +| Import | `import { CometChatLocalize } from "@cometchat/chat-uikit-react";` | +| Set language | `CometChatLocalize.setCurrentLanguage("fr")` | +| Init with config | `CometChatLocalize.init({ language: "es", fallbackLanguage: "en-US", disableAutoDetection: false })` | +| Add translations | `CometChatLocalize.addTranslation({ "en-US": { "welcome_message": "Welcome!" } })` | +| Supported languages | 19: en-US, en-GB, nl, fr, de, hi, it, ja, ko, pt, ru, es, tr, zh, zh-TW, ms, sv, lt, hu | +| Date formatting | Use `CalendarObject` for custom date/time patterns | +| Source | [GitHub](https://github.com/cometchat/cometchat-uikit-react/blob/v6/src/resources/CometChatLocalize/cometchat-localize.ts) | -* **Automatically detect and apply a language** based on browser/device settings. -* **Manually change the UI language**. -* **Format date and time** based on localization settings. + -The v6 React UI Kit expands support for **multiple languages** and allows developers to define **custom translations**.\ -The localization system now includes **language JSON files**, which store translations, and an **improved CometChatLocalize class**, which handles language detection and formatting. +The `CometChatLocalize` class manages multi-language localization for the UI Kit. It handles automatic language detection, manual language switching, custom translations, and date/time formatting. -*** - -### **Supported Languages** +--- -React UI Kit currently supports **19 languages**: +## Supported Languages -| Language | Code | -| ------------------------ | ------- | -| English (United States) | `en-US` | +| Language | Code | +| --- | --- | +| English (United States) | `en-US` | | English (United Kingdom) | `en-GB` | -| Dutch | `nl` | -| French | `fr` | -| German | `de` | -| Hindi | `hi` | -| Italian | `it` | -| Japanese | `ja` | -| Korean | `ko` | -| Portuguese | `pt` | -| Russian | `ru` | -| Spanish | `es` | -| Turkish | `tr` | -| Chinese | `zh` | -| Chinese (Traditional) | `zh-TW` | -| Malay | `ms` | -| Swedish | `sv` | -| Lithuanian | `lt` | -| Hungarian | `hu` | - -🔗 **View JSON files for all supported languages** in the GitHub repository:\ -➡ [Language JSON Files](https://github.com/cometchat/cometchat-uikit-react/tree/v6/src/resources/CometChatLocalize/resources) - -*** - -## **CometChatLocalize** +| Dutch | `nl` | +| French | `fr` | +| German | `de` | +| Hindi | `hi` | +| Italian | `it` | +| Japanese | `ja` | +| Korean | `ko` | +| Portuguese | `pt` | +| Russian | `ru` | +| Spanish | `es` | +| Turkish | `tr` | +| Chinese | `zh` | +| Chinese (Traditional) | `zh-TW` | +| Malay | `ms` | +| Swedish | `sv` | +| Lithuanian | `lt` | +| Hungarian | `hu` | + +[Language JSON files on GitHub](https://github.com/cometchat/cometchat-uikit-react/tree/v6/src/resources/CometChatLocalize/resources) -The `CometChatLocalize` class provides methods for managing localization in the UI Kit. - -🔗 **View full class file in the GitHub repository:**\ -➡ [CometChatLocalize](https://github.com/cometchat/cometchat-uikit-react/blob/v6/src/resources/CometChatLocalize/cometchat-localize.ts) - -*** - -### **LocalizationSettings** +--- -The `LocalizationSettings` interface defines various **localization settings** for an application or component. It allows developers to configure the language, translations, time zone, and calendar formatting while providing options for automatic detection and missing key handling. +## LocalizationSettings -| Property | Type | Description | -| ----------------------------- | ------------------------- | --------------------------------------------------------------------------------------------------- | -| `language` | `string` | The language code (e.g., `"en"`, `"fr"`) for the current localization. | -| `translationsForLanguage` | `{ [key: string]: any }` | An object containing key-value pairs for translations in the current language. | -| `disableAutoDetection` | `boolean` | Disables automatic language detection based on the browser or device settings. | -| `fallbackLanguage` | `string` | The **fallback language code** to use if the primary language is not available. | -| `disableDateTimeLocalization` | `boolean` | Disables localization for **date and time values**, forcing the default format. | -| `timezone` | `string` | The **timezone** used for date and time formatting (e.g., `"America/New_York"`, `"Europe/London"`). | -| `calendarObject` | `CalendarObject` | A **custom calendar format** using `CalendarObject` to define localized date and time formatting. | -| `missingKeyHandler` | `(key: string) => string` | A function that **handles missing translation keys**, allowing custom error handling or fallbacks. | +Configuration interface for `CometChatLocalize.init()`. -*** +| Property | Type | Description | +| --- | --- | --- | +| `language` | `string` | Language code (e.g., `"en"`, `"fr"`) for the current localization | +| `translationsForLanguage` | `{ [key: string]: any }` | Key-value pairs for translations in the current language | +| `disableAutoDetection` | `boolean` | Disables automatic language detection based on browser/device settings | +| `fallbackLanguage` | `string` | Fallback language code if the primary language is not available | +| `disableDateTimeLocalization` | `boolean` | Disables localization for date and time values, forcing the default format | +| `timezone` | `string` | Timezone for date and time formatting (e.g., `"America/New_York"`, `"Europe/London"`) | +| `calendarObject` | `CalendarObject` | Custom calendar format for localized date and time formatting | +| `missingKeyHandler` | `(key: string) => void` | Handles missing translation keys with custom error handling or fallbacks | -**Example** ```javascript import { CometChatLocalize } from "@cometchat/chat-uikit-react"; import { CalendarObject } from "./CalendarObject"; CometChatLocalize.init({ - language: "es", // Default language set to Spanish - fallbackLanguage: "en-US", // Use English if the preferred language is not available + language: "es", + fallbackLanguage: "en-US", translationsForLanguage: { "es": { "welcome_message": "¡Bienvenido a CometChat!", @@ -92,9 +84,9 @@ CometChatLocalize.init({ "logout_message": "Vous vous êtes déconnecté avec succès." } }, - disableAutoDetection: false, // Allow automatic detection of browser/device language - disableDateTimeLocalization: false, // Enable localization for date and time - timezone: "Europe/Madrid", // Set time zone for date and time formatting + disableAutoDetection: false, + disableDateTimeLocalization: false, + timezone: "Europe/Madrid", calendarObject: new CalendarObject({ today: "[Hoy a las] hh:mm A", yesterday: "[Ayer a las] hh:mm A", @@ -107,83 +99,62 @@ CometChatLocalize.init({ hours: "%d horas atrás", } }), - missingKeyHandler: (key) => `🔍 Missing translation for: ${key}`, // Custom handler for missing translations + missingKeyHandler: (key) => `Missing translation for: ${key}`, }); ``` -*** +--- -### **CalendarObject** +## CalendarObject -The `CalendarObject` class defines customizable formatting for date and time representation. It allows you to format dates based on whether they are today, yesterday, last week, or other days. It also supports relative time formatting for minutes and hours. +Defines customizable formatting for date and time representation. Supports relative time formatting for minutes and hours. -Notice - -Changing this format will **globally update** the date and time representation wherever it is used in the component.\ -However, if a **component-specific** `CalendarObject` is provided, it will take **higher precedence** over the global settings. - +Changing this format globally updates the date and time representation wherever it is used. If a component-specific `CalendarObject` is provided, it takes higher precedence over the global settings. -| Property | Type | Description | -| ---------------------- | -------- | ----------------------------------------------------------------------------------------------- | -| `today` | `string` | Custom formatting for dates that fall on the same day. Example: `"Today at hh:mm A"` | -| `yesterday` | `string` | Custom formatting for dates that fall on the previous day. Example: `"Yesterday at hh:mm A"` | -| `lastWeek` | `string` | Custom formatting for dates within the last 7 days. Example: `"Last week on dddd"` | -| `otherDays` | `string` | Custom formatting for dates that do not fit other categories. Example: `"DD MMM YYYY, hh:mm A"` | -| `relativeTime` | `object` | Custom formatting for relative time expressions (e.g., "2 hours ago"). | -| `relativeTime.minute` | `string` | Formatting for a single minute. Example: `"%d minute ago"` | -| `relativeTime.minutes` | `string` | Formatting for multiple minutes. Example: `"%d minutes ago"` | -| `relativeTime.hour` | `string` | Formatting for a single hour. Example: `"%d hour ago"` | -| `relativeTime.hours` | `string` | Formatting for multiple hours. Example: `"%d hours ago"` | - -*** - -**Example** +| Property | Type | Description | +| --- | --- | --- | +| `today` | `string` | Format for dates on the same day. Example: `"Today at hh:mm A"` | +| `yesterday` | `string` | Format for dates on the previous day. Example: `"Yesterday at hh:mm A"` | +| `lastWeek` | `string` | Format for dates within the last 7 days. Example: `"Last week on dddd"` | +| `otherDays` | `string` | Format for dates that do not fit other categories. Example: `"DD MMM YYYY, hh:mm A"` | +| `relativeTime` | `object` | Custom formatting for relative time expressions | +| `relativeTime.minute` | `string` | Single minute format. Example: `"%d minute ago"` | +| `relativeTime.minutes` | `string` | Multiple minutes format. Example: `"%d minutes ago"` | +| `relativeTime.hour` | `string` | Single hour format. Example: `"%d hour ago"` | +| `relativeTime.hours` | `string` | Multiple hours format. Example: `"%d hours ago"` | ```javascript -import { CometChatLocalize } from "@cometchat/chat-uikit-react"; -import { CalendarObject } from "./CalendarObject"; - new CalendarObject({ - today: "[Hoy a las] hh:mm A", - yesterday: "[Ayer a las] hh:mm A", - lastWeek: "[Última semana el] dddd", - otherDays: "DD MMM YYYY, hh:mm A", - relativeTime: { - minute: "%d minuto atrás", - minutes: "%d minutos atrás", - hour: "%d hora atrás", - hours: "%d horas atrás", - } - }) + today: "[Hoy a las] hh:mm A", + yesterday: "[Ayer a las] hh:mm A", + lastWeek: "[Última semana el] dddd", + otherDays: "DD MMM YYYY, hh:mm A", + relativeTime: { + minute: "%d minuto atrás", + minutes: "%d minutos atrás", + hour: "%d hora atrás", + hours: "%d horas atrás", + } +}) ``` -*** +--- -### **Component Guide** +## Component Guide -Note - -The translation configurations mentioned in this section are to be defined inside the -ComeChat's init() method callback. +The translation configurations in this section are to be defined inside the [CometChat's init() method callback](/ui-kit/react/react-js-integration#step-3:-initialize-cometchat-ui-kit). -#### Report Message - -To add translations for any flag reason, a key in the form of `flag_message_reason_id_{reason_id}` is to be defined with the translated strings to be displayed for that `reason_id` in the UI. The translations for `flag_message_reason_id_spam`, `flag_message_reason_id_sexual`, `flag_message_reason_id_harassment` are present by default. - -**Usage** -* Define translations for custom flag message reasons. -* The reason name would be displayed when the required translation is not found. +### Report Message -**Example** +To add translations for any flag reason, define a key in the form `flag_message_reason_id_{reason_id}` with the translated strings. Translations for `flag_message_reason_id_spam`, `flag_message_reason_id_sexual`, `flag_message_reason_id_harassment` are present by default. The reason name is displayed when the required translation is not found. ```javascript import { CometChatLocalize } from "@cometchat/chat-uikit-react"; -// Add translations for flag reason keys for the required languages CometChatLocalize.addTranslation({ "en-GB": { "flag_message_reason_id_dislike": "I just don't like it", @@ -194,20 +165,13 @@ CometChatLocalize.addTranslation({ }); ``` -#### Mention All +### Mention All -To add translations for a custom `mentionAllLabel`, a key in the form of `message_composer_mention_{label}` is to be defined with the translated strings to be displayed for that label in the UI. The translations for `message_composer_mention_all` is present by default. - -**Usage** -* Define translations for custom mentionAllLabel. -* Helps customize the `@all` label used in the app while mentioning all group members. - -**Example** +To add translations for a custom `mentionAllLabel`, define a key in the form `message_composer_mention_{label}`. The translation for `message_composer_mention_all` is present by default. ```javascript import { CometChatLocalize } from "@cometchat/chat-uikit-react"; -// Add translations for mentionAllLabel for the required languages CometChatLocalize.addTranslation({ "en-GB": { "message_composer_mention_channel": "channel", @@ -218,169 +182,131 @@ CometChatLocalize.addTranslation({ }); ``` -*** - -### **Methods** - -#### Initialize CometChatLocalize - -This method initializes the localization system with default values and optional configurations. +--- -**Usage** +## Methods -* Set the default language, timezone, and fallback settings. -* Define a custom calendar format if required. -* Customize how missing keys are handled. +### init -**Example** +Initializes the localization system with default values and optional configurations. ```javascript import { CometChatLocalize } from "@cometchat/chat-uikit-react"; -// Initialize localization settings CometChatLocalize.init({ - language: "es", // Default language: Spanish - fallbackLanguage: "en-US", // Fallback if translation is missing - disableAutoDetection: false, // Enable browser language detection + language: "es", + fallbackLanguage: "en-US", + disableAutoDetection: false, timezone: "Europe/Madrid", missingKeyHandler: (key) => `Missing translation: ${key}`, }); ``` -*** - -#### Get Browser Language - -This method detects the language set in the user's browser or device settings. - -**Usage** +### getBrowserLanguage -* Automatically set the app’s language based on the user’s browser settings. -* Helps in making the UI multilingual without requiring user input. - -**Example** +Detects the language set in the user's browser or device settings. ```javascript const userLang = CometChatLocalize.getBrowserLanguage(); console.log(userLang); ``` -*** - -#### Get Localized String - -This method fetches localized text based on the current language. - -**Usage** - -* Retrieve translations dynamically without hardcoding values in multiple languages. -* Useful for UI elements, buttons, alerts, and system messages. +### getLocalizedString -**Example** +Fetches localized text based on the current language. ```javascript const translatedText = CometChatLocalize.getLocalizedString("welcome_message"); ``` -*** +### getCurrentLanguage -#### Get Current Language - -This method returns the currently set language for the UI Kit. - -**Usage** - -* Useful to debug and display the currently active language. -* Helps when dynamically switching between languages. - -**Example** +Returns the currently set language for the UI Kit. ```javascript console.log(CometChatLocalize.getCurrentLanguage()); ``` -*** - -#### Get Default Language +### getDefaultLanguage -This method returns the system-preferred language. - -**Usage** - -* If disableAutoDetection is enabled, the method returns the fallback language. -* If auto-detection is enabled, it returns the browser's preferred language. - -**Example** +Returns the system-preferred language. If `disableAutoDetection` is enabled, returns the fallback language. Otherwise returns the browser's preferred language. ```javascript console.log(CometChatLocalize.getDefaultLanguage()); ``` -*** - -#### Set Current Language +### setCurrentLanguage -This method updates the language at runtime without reloading the application. - -**Usage** - -* Allow users to change the language via a settings menu. -* Ensure that UI elements are updated instantly after changing the language. - -**Example** +Updates the language at runtime without reloading the application. ```javascript CometChatLocalize.setCurrentLanguage("fr"); ``` -*** +### addTranslation -#### Add Custom Translations +Adds custom translations to the existing ones dynamically. New translations are merged into the existing localization data. + +```javascript +CometChatLocalize.addTranslation({ + "en-US": { "welcome_message": "Welcome to CometChat!" } +}); +``` -This method allows you to add custom translations to the existing ones dynamically. It ensures that new translations are merged into the existing localization data. +### formatDate -**Usage** +Formats a Unix timestamp (seconds) based on a `CalendarObject` configuration. Uses the timezone set via `init()`. -* You can define custom translation keys and override the existing translations. -* You can add new languages to the existing translations. -* Useful when you want to support additional words or phrases not present in the default language files. +| Parameter | Type | Description | +| --- | --- | --- | +| `timestamp` | `number` | Unix timestamp in seconds | +| `calendarObject` | `CalendarObject` | Calendar configuration for formatting | -**Example** +Returns a formatted date `string`. ```javascript -CometChatLocalize.addTranslation({ - "en-US": { "welcome_message": "Welcome to CometChat!" } -}); +import { CometChatLocalize } from "@cometchat/chat-uikit-react"; +import { CalendarObject } from "@cometchat/chat-uikit-react"; + +const formatted = CometChatLocalize.formatDate(1700000000, new CalendarObject({ + today: "hh:mm A", + yesterday: "[Yesterday]", + lastWeek: "dddd", + otherDays: "DD MMM YYYY, hh:mm A" +})); ``` -*** +### getDateLocaleLanguage -#### **Customisation** +Returns the language code used for date localization. If `disableDateTimeLocalization` is `true`, returns `"en-US"`. Otherwise returns the current language. -CometChat UI Kit provides **flexible customization options** for date/time format. Users can configure **global settings** using `CometChatLocalize.init()` or pass a `CalendarObject` directly to individual components for **component-specific** customization. +```javascript +const dateLang = CometChatLocalize.getDateLocaleLanguage(); +``` -* **Global Configuration:** When settings are provided in `CometChatLocalize.init()`, all UI components will automatically use the configured date/time formats. -* **Component-Specific Configuration:** If a `CalendarObject` is passed to a component, it **overrides** the global settings and applies only to that specific instance. +--- + +## Customization -**Global Configuration Example** +### Global Configuration -To apply a **custom date format** globally across the whole UI Kit. +Apply a custom date format globally across the whole UI Kit via `CometChatLocalize.init()`: -```php +```javascript CometChatLocalize.init({ - calendarObject:new CalendarObject({ - today: " hh:mm A", - yesterday: "[Yesterday], + calendarObject: new CalendarObject({ + today: "hh:mm A", + yesterday: "[Yesterday]", otherDays: "DD MMM YYYY, hh:mm A" }) }); ``` -**Component-Specific Customization Example** +### Component-Specific Configuration -To apply a **custom date format** only within a specific component. +Apply a custom date format only within a specific component. Component-level `CalendarObject` overrides the global settings. -```csharp +```tsx ``` - -*** \ No newline at end of file diff --git a/ui-kit/react/mentions-formatter-guide.mdx b/ui-kit/react/mentions-formatter-guide.mdx index f5e8d6860..1d0626569 100644 --- a/ui-kit/react/mentions-formatter-guide.mdx +++ b/ui-kit/react/mentions-formatter-guide.mdx @@ -1,7 +1,18 @@ --- title: "Mentions Formatter" +description: "Add @mentions with styled tokens, suggestion list, and click handling in CometChat React UI Kit." --- + +- **Package:** `@cometchat/chat-uikit-react` +- **Key class:** `CometChatMentionsFormatter` (extends `CometChatTextFormatter`) +- **Required setup:** `CometChatUIKit.init(UIKitSettings)` then `CometChatUIKit.login("UID")` +- **Purpose:** Format @mentions with styled tokens, suggestion list, and click handling for users and group members +- **Sample app:** [GitHub](https://github.com/cometchat/cometchat-uikit-react/tree/v6/sample-app) +- **Related:** [Custom Text Formatter](/ui-kit/react/custom-text-formatter-guide) | [All Guides](/ui-kit/react/guide-overview) + + + ## Overview The `CometChatMentionsFormatter` class is a part of the CometChat UI Kit, a ready-to-use chat UI component library for integrating CometChat into your React applications. This class provides functionality to format mentions within text messages displayed in the chat interface. Mentions allow users to reference other users within a conversation, providing a convenient way to direct messages or involve specific participants. @@ -48,3 +59,22 @@ mentionsFormatter.setCometChatUserGroupMembers(userList); The `formattedMessage` now contains HTML with styled mentions, ready to be inserted into your message component for display. Below is an example demonstrating how to use the `CometChatMentionsFormatter` class in components such as [CometChatConversations](/ui-kit/react/conversations), [CometChatMessageList](/ui-kit/react/message-list), [CometChatMessageComposer](/ui-kit/react/message-composer). + +## Next Steps + + + + Build custom inline text patterns. + + + Render real-time message threads. + + + Browse all feature and formatter guides. + + + Full working sample application on GitHub. + + + +*** diff --git a/ui-kit/react/message-composer.mdx b/ui-kit/react/message-composer.mdx index 67249e000..42ef95cb3 100644 --- a/ui-kit/react/message-composer.mdx +++ b/ui-kit/react/message-composer.mdx @@ -1,922 +1,940 @@ --- title: "Message Composer" +description: "Rich text input for composing and sending text, media, attachments, mentions, voice notes, and custom messages." --- + +```json +{ + "component": "CometChatMessageComposer", + "package": "@cometchat/chat-uikit-react", + "import": "import { CometChatMessageComposer } from \"@cometchat/chat-uikit-react\";", + "cssImport": "import \"@cometchat/chat-uikit-react/css-variables.css\";", + "description": "Rich text input for composing and sending text, media, attachments, mentions, voice notes, and custom messages.", + "cssRootClass": ".cometchat-message-composer", + "primaryOutput": { + "prop": "onSendButtonClick", + "type": "(message: CometChat.BaseMessage, previewMessageMode?: PreviewMessageMode) => void" + }, + "props": { + "data": { + "user": { "type": "CometChat.User", "default": "undefined" }, + "group": { "type": "CometChat.Group", "default": "undefined" }, + "parentMessageId": { "type": "number", "default": "undefined" }, + "initialComposerText": { "type": "string", "default": "\"\"" }, + "placeholderText": { "type": "string", "default": "\"\"" } + }, + "callbacks": { + "onSendButtonClick": "(message: CometChat.BaseMessage, previewMessageMode?: PreviewMessageMode) => void", + "onTextChange": "(text: string) => void", + "onError": "((error: CometChat.CometChatException) => void) | null" + }, + "visibility": { + "hideImageAttachmentOption": { "type": "boolean", "default": false }, + "hideVideoAttachmentOption": { "type": "boolean", "default": false }, + "hideAudioAttachmentOption": { "type": "boolean", "default": false }, + "hideFileAttachmentOption": { "type": "boolean", "default": false }, + "hidePollsOption": { "type": "boolean", "default": false }, + "hideCollaborativeDocumentOption": { "type": "boolean", "default": false }, + "hideCollaborativeWhiteboardOption": { "type": "boolean", "default": false }, + "hideAttachmentButton": { "type": "boolean", "default": false }, + "hideVoiceRecordingButton": { "type": "boolean", "default": false }, + "hideEmojiKeyboardButton": { "type": "boolean", "default": false }, + "hideStickersButton": { "type": "boolean", "default": false }, + "hideSendButton": { "type": "boolean", "default": false }, + "showScrollbar": { "type": "boolean", "default": false } + }, + "behavior": { + "disableTypingEvents": { "type": "boolean", "default": false }, + "disableMentions": { "type": "boolean", "default": false }, + "disableMentionAll": { "type": "boolean", "default": false }, + "mentionAllLabel": { "type": "string", "default": "\"all\"" }, + "enterKeyBehavior": { "type": "EnterKeyBehavior", "default": "EnterKeyBehavior.SendMessage" }, + "disableSoundForMessage": { "type": "boolean", "default": false }, + "customSoundForMessage": { "type": "string", "default": "undefined" } + }, + "mentions": { + "mentionsUsersRequestBuilder": "CometChat.UsersRequestBuilder", + "mentionsGroupMembersRequestBuilder": "CometChat.GroupMembersRequestBuilder" + }, + "viewSlots": { + "attachmentOptions": "CometChatMessageComposerAction[]", + "auxiliaryButtonView": "JSX.Element", + "sendButtonView": "JSX.Element", + "headerView": "JSX.Element" + }, + "formatting": { + "textFormatters": { "type": "CometChatTextFormatter[]", "default": "default formatters" } + } + }, + "events": [ + { "name": "CometChatMessageEvents.ccMessageSent", "payload": "IMessages" }, + { "name": "CometChatMessageEvents.ccMessageEdited", "payload": "IMessages" }, + { "name": "CometChatMessageEvents.ccReplyToMessage", "payload": "IMessages" } + ], + "sdkListeners": [], + "types": { + "EnterKeyBehavior": { "SendMessage": "sendMessage", "NewLine": "newLine", "None": "none" }, + "PreviewMessageMode": { "edit": 0, "none": 1 } + } +} +``` + + +## Where It Fits + +`CometChatMessageComposer` provides a rich text input with attachment, emoji, voice recording, sticker, and send controls. Wire it alongside `CometChatMessageHeader` and `CometChatMessageList` to build a standard chat view. + +```tsx +import { useState, useEffect } from "react"; +import { CometChat } from "@cometchat/chat-sdk-javascript"; +import { + CometChatMessageHeader, + CometChatMessageList, + CometChatMessageComposer, +} from "@cometchat/chat-uikit-react"; +import "@cometchat/chat-uikit-react/css-variables.css"; -## Overview +function ChatView() { + const [chatUser, setChatUser] = useState(); -MessageComposer is a Component that enables users to write and send a variety of messages, including text, image, video, and custom messages. + useEffect(() => { + CometChat.getUser("uid").then((user) => setChatUser(user)); + }, []); -Features such as **Attachments**, and **Message Editing** are also supported by it. + return chatUser ? ( +
+ + + +
+ ) : null; +} +``` -## Usage - -### Integration +--- -The following code snippet illustrates how you can directly incorporate the MessageComposer component into your app. +## Minimal Render - - ```tsx -import React from "react"; +import { useState, useEffect } from "react"; import { CometChat } from "@cometchat/chat-sdk-javascript"; import { CometChatMessageComposer } from "@cometchat/chat-uikit-react"; +import "@cometchat/chat-uikit-react/css-variables.css"; + +function MessageComposerDemo() { + const [chatUser, setChatUser] = useState(); -export function MessageComposerDemo() { - const [chatUser, setChatUser] = React.useState(); - React.useEffect(() => { - CometChat.getUser("uid").then((user) => { - setChatUser(user); - }); + useEffect(() => { + CometChat.getUser("uid").then((user) => setChatUser(user)); }, []); - return chatUser ? ( -
- -
- ) : null; + return chatUser ? : null; } + +export default MessageComposerDemo; ``` -
+Root CSS class: `.cometchat-message-composer` + +--- + +## Actions and Events + +### Callback Props + +#### onSendButtonClick + +Fires when the send button is clicked. Overrides the default send behavior. - ```tsx -import { MessageComposerDemo } from "./MessageComposerDemo"; +import { CometChatMessageComposer } from "@cometchat/chat-uikit-react"; +import { CometChat } from "@cometchat/chat-sdk-javascript"; -export default function App() { +function ComposerWithCustomSend() { return ( -
-
- -
-
+ { + console.log("Custom send:", message); + }} + /> ); } ``` -
+#### onTextChange -
+Fires as the user types in the composer input. -### Actions +```tsx +import { CometChatMessageComposer } from "@cometchat/chat-uikit-react"; -[Actions](/ui-kit/react/components-overview#actions) dictate how a component functions. They are divided into two types: Predefined and User-defined. You can override either type, allowing you to tailor the behavior of the component to fit your specific needs. +function ComposerWithTextTracking() { + return ( + { + console.log("Text changed:", text); + }} + /> + ); +} +``` -##### 1. OnSendButtonClick +#### onError -The `OnSendButtonClick` event gets activated when the send message button is clicked. It has a predefined function of sending messages entered in the composer `EditText`. However, you can overide this action with the following code snippet. +Fires on internal errors. - - ```tsx -import React from "react"; -import { CometChat } from "@cometchat/chat-sdk-javascript"; import { CometChatMessageComposer } from "@cometchat/chat-uikit-react"; +import { CometChat } from "@cometchat/chat-sdk-javascript"; -export function MessageComposerDemo() { - const [chatUser, setChatUser] = React.useState(); +function ComposerWithError() { + return ( + { + console.error("Composer error:", error); + }} + /> + ); +} +``` - React.useEffect(() => { - CometChat.getUser("uid").then((user) => { - setChatUser(user); - }); - }, []); +### Global UI Events - function handleSendButtonClick(message: CometChat.BaseMessage): void { - console.log("your custom on send buttonclick action"); - } +| Event | Fires when | Payload | +| --- | --- | --- | +| `CometChatMessageEvents.ccMessageSent` | A message is sent | `IMessages` | +| `CometChatMessageEvents.ccMessageEdited` | A message is edited | `IMessages` | +| `CometChatMessageEvents.ccReplyToMessage` | User replies to a message | `IMessages` | - return chatUser ? ( -
- -
- ) : null; +```tsx +import { useEffect } from "react"; +import { CometChatMessageEvents } from "@cometchat/chat-uikit-react"; + +function useComposerEvents() { + useEffect(() => { + const sentSub = CometChatMessageEvents.ccMessageSent.subscribe( + (data) => console.log("Sent:", data) + ); + const editedSub = CometChatMessageEvents.ccMessageEdited.subscribe( + (data) => console.log("Edited:", data) + ); + + return () => { + sentSub?.unsubscribe(); + editedSub?.unsubscribe(); + }; + }, []); } ``` -
+### SDK Events (Real-Time, Automatic) -
+The component internally handles typing indicators and message sending. No manual SDK listener attachment needed. -##### 2. onError +--- -This action doesn't change the behavior of the component but rather listens for any errors that occur in the MessageList component. +## Custom View Slots + +| Slot | Type | Replaces | +| --- | --- | --- | +| `attachmentOptions` | `CometChatMessageComposerAction[]` | Default attachment options list | +| `auxiliaryButtonView` | `JSX.Element` | Sticker and AI button area | +| `sendButtonView` | `JSX.Element` | Send button | +| `headerView` | `JSX.Element` | Area above the composer input | + +### attachmentOptions + +Override the default attachment options. + + + + - - ```tsx -import React from "react"; -import { CometChat } from "@cometchat/chat-sdk-javascript"; -import { CometChatMessageComposer } from "@cometchat/chat-uikit-react"; +import { + CometChatMessageComposer, + CometChatMessageComposerAction, +} from "@cometchat/chat-uikit-react"; -export function MessageComposerDemo() { - const [chatUser, setChatUser] = React.useState(); +function ComposerCustomAttachments() { + return ( + + ); +} +``` - React.useEffect(() => { - CometChat.getUser("uid").then((user) => { - setChatUser(user); - }); - }, []); +### auxiliaryButtonView - function handleError(error: CometChat.CometChatException) { - throw new Error("your custom error action"); - } +Replace the sticker and AI button area. - return chatUser ? ( -
- -
- ) : null; + + + + +```tsx +import { + CometChatMessageComposer, + CometChatButton, +} from "@cometchat/chat-uikit-react"; + +function ComposerCustomAuxiliary() { + return ( + {}} /> + } + /> + ); } ``` +### sendButtonView + +Replace the send button. + + + + + + + +```tsx +import { + CometChatMessageComposer, + CometChatButton, +} from "@cometchat/chat-uikit-react"; + +function ComposerCustomSend() { + return ( + {}} /> + } + /> + ); +} +``` + +```css +.cometchat-message-composer div:not([class]) .message-composer__send-button .cometchat-button { + background: #edeafa; +} +.cometchat-message-composer div:not([class]) .message-composer__send-button .cometchat-button__icon { + background: #6852d6; +} +``` + -##### 3. onTextChange +### headerView + +Custom view above the composer input. -This event is triggered as the user starts typing in the Message Composer. + + + - + ```tsx -import React from "react"; -import { CometChat } from "@cometchat/chat-sdk-javascript"; import { CometChatMessageComposer } from "@cometchat/chat-uikit-react"; -export function MessageComposerDemo() { - const [chatUser, setChatUser] = React.useState(); - - React.useEffect(() => { - CometChat.getUser("uid").then((user) => { - setChatUser(user); - }); - }, []); +function ComposerWithHeader() { + return ( + +
+
+ User has paused their notifications +
+
+ } + /> + ); +} +``` +
+ +```css +.cometchat-message-composer .message-composer__header-view { + display: flex; + align-items: center; + gap: 8px; + width: 100%; +} - function handleTextChange(text: string) { - console.log("onTextChange", text); - } +.cometchat-message-composer__header { + background: #dcd7f6; + border-radius: var(--cometchat-radius-max, 1000px); + padding: var(--cometchat-padding-2) var(--cometchat-padding-5); +} - return chatUser ? ( -
- -
- ) : null; +.message-composer__header-view-text { + color: var(--cometchat-text-color-primary); + font: var(--cometchat-font-body-regular); } ``` -
-
-##### 4. Custom Mentions Request Builders +--- -You can customize how mentioned users and group members are fetched by providing custom request builders. +## Common Patterns + +### Thread composer - - ```tsx -import React from "react"; -import { CometChat } from "@cometchat/chat-sdk-javascript"; import { CometChatMessageComposer } from "@cometchat/chat-uikit-react"; -export function MessageComposerDemo() { - const [chatUser, setChatUser] = React.useState(); - const [chatGroup, setChatGroup] = React.useState(); - - React.useEffect(() => { - CometChat.getUser("uid").then((user) => { - setChatUser(user); - }); - CometChat.getGroup("guid").then((group) => { - setChatGroup(group); - }); - }, []); +function ThreadComposer() { + return ( + + ); +} +``` - // Custom Users Request Builder for mentions - const mentionsUsersRequestBuilder = new CometChat.UsersRequestBuilder() - .setLimit(10) - .setSearchKeyword("") - .setRoles(["default", "moderator"]); +### Minimal composer — text only - // Custom Group Members Request Builder for group mentions - const mentionsGroupMembersRequestBuilder = new CometChat.GroupMembersRequestBuilder("guid") - .setLimit(15) - .setSearchKeyword("") - .setScopes(["admin", "moderator", "participant"]); +```tsx +import { CometChatMessageComposer } from "@cometchat/chat-uikit-react"; - return chatUser ? ( -
- {/* For user chat with custom users mentions */} - - - {/* For group chat with custom group members mentions */} - {chatGroup && ( - - )} -
- ) : null; +function MinimalComposer() { + return ( + + ); } ``` -
+### Enter key adds new line -
+```tsx +import { CometChatMessageComposer, EnterKeyBehavior } from "@cometchat/chat-uikit-react"; -*** +function NewLineComposer() { + return ( + + ); +} +``` -### Filters +### Pre-filled text -MessageComposer component does not have any available filters. +```tsx +import { CometChatMessageComposer } from "@cometchat/chat-uikit-react"; -*** +function PrefilledComposer() { + return ( + + ); +} +``` -### Events +--- -[Events](/ui-kit/react/components-overview#events) are emitted by a `Component`. By using event you can extend existing functionality. Being global events, they can be applied in Multiple Locations and are capable of being Added or Removed. +## CSS Architecture -The list of events emitted by the Messages component is as follows. +The component uses CSS custom properties (design tokens) defined in `@cometchat/chat-uikit-react/css-variables.css`. The cascade: -| Event | Description | -| ------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------ | -| **ccMessageEdited** | Triggers whenever a loggedIn user edits any message from the list of messages .it will have three states such as: inProgress, success and error. | -| **ccReplyToMessage** | Triggers whenever a loggedIn user replies to any message from the list of messages .it will have three states such as: inProgress, success and error. | -| **ccMessageSent** | Triggers whenever a loggedIn user sends any message, it will have three states such as: inProgress, success and error. | +1. Global tokens set on the `.cometchat` root wrapper. +2. Component CSS (`.cometchat-message-composer`) consumes these tokens via `var()`. +3. Overrides target `.cometchat-message-composer` descendant selectors. -Adding `CometChatMessageEvents` Listener's +### Key Selectors - - -```js -import { CometChatMessageEvents } from "@cometchat/chat-uikit-react"; +| Target | Selector | +| --- | --- | +| Root | `.cometchat-message-composer` | +| Send button | `.cometchat-message-composer__send-button` | +| Send button active | `.cometchat-message-composer__send-button-active` | +| Sticker button popover | `.cometchat-message-composer__auxilary-button-view-sticker-button .cometchat-popover__content` | +| Emoji keyboard popover | `.cometchat-message-composer__emoji-keyboard-button .cometchat-popover__content` | +| Attachment popover | `.cometchat-message-composer__secondary-button-view-attachment-button .cometchat-popover__content` | +| Voice recording popover | `.cometchat-message-composer__voice-recording-button .cometchat-popover__content` | +| Header area | `.cometchat-message-composer__header` | -const ccMessageEdited = CometChatMessageEvents.ccMessageEdited.subscribe(() => { - // Your Code -}); +### Customization Matrix -const ccReplyToMessage = CometChatMessageEvents.ccReplyToMessage.subscribe(() => { - // Your Code -}); +| What to change | Where | Property/API | Example | +| --- | --- | --- | --- | +| Override send behavior | Component props | `onSendButtonClick` | `onSendButtonClick={(msg) => customSend(msg)}` | +| Track text input | Component props | `onTextChange` | `onTextChange={(text) => track(text)}` | +| Toggle visibility | Component props | `hide` boolean props | `hideAttachmentButton={true}` | +| Custom attachments | Component props | `attachmentOptions` | `attachmentOptions={[new CometChatMessageComposerAction(...)]}` | +| Replace UI sections | Component props | View slot props | `sendButtonView={
...
}` | +| Change Enter key behavior | Component props | `enterKeyBehavior` | `enterKeyBehavior={EnterKeyBehavior.NewLine}` | +| Change colors, fonts, spacing | Global CSS | Target `.cometchat-message-composer` class | `.cometchat-message-composer__send-button { background: blue; }` | -const ccMessageSent = CometChatMessageEvents.ccMessageSent.subscribe(() => { - // Your Code -}); -``` +--- -
+## Accessibility -
+The text input is auto-focused and supports standard keyboard shortcuts. The send button activates on Enter (configurable via `enterKeyBehavior`). Attachment, emoji, sticker, and voice recording buttons are keyboard-focusable and activate on Enter/Space. The mention suggestions list is keyboard-navigable with arrow keys. -*** +--- -Removing `CometChatMessageEvents` Listener's +--- - - -```js -ccMessageEdited?.unsubscribe(); -ccReplyToMessage?.unsubscribe(); -ccMessageSent?.unsubscribe(); -``` +## Props - +All props are optional. Sorted alphabetically. - +### attachmentOptions -*** +Custom attachment options list. -## Customization +| | | +| --- | --- | +| Type | `CometChatMessageComposerAction[]` | +| Default | `undefined` | -To fit your app's design requirements, you can customize the appearance of the MessageComposer component. We provide exposed methods that allow you to modify the experience and behavior according to your specific needs. +--- -### Style +### auxiliaryButtonView -To modify the styling, you can customise the css of MessageComposer Component. +Custom JSX replacing the sticker and AI button area. -**Example** +| | | +| --- | --- | +| Type | `JSX.Element` | +| Default | Built-in sticker/AI buttons | - - - +--- - - -```tsx -import React from "react"; -import { CometChat } from "@cometchat/chat-sdk-javascript"; -import { CometChatMessageComposer } from "@cometchat/chat-uikit-react"; +### customSoundForMessage -; -``` +URL to a custom audio file for outgoing message notifications. - +| | | +| --- | --- | +| Type | `string` | +| Default | `undefined` | - -```css -.cometchat-message-composer .cometchat-message-composer__input { - font-family: "SF Pro"; -} +--- -.cometchat-message-composer .cometchat-button .cometchat-button__icon { - background: #f19fa1; -} +### disableMentionAll -.cometchat-message-composer .cometchat-message-composer__send-button { - background: #e5484d; +Controls whether group mentions like @all appear in suggestions. + +| | | +| --- | --- | +| Type | `boolean` | +| Default | `false` | + +--- + +### disableMentions + +Disables the mentions functionality. + +| | | +| --- | --- | +| Type | `boolean` | +| Default | `false` | + +--- + +### disableSoundForMessage + +Disables sound for outgoing messages. + +| | | +| --- | --- | +| Type | `boolean` | +| Default | `false` | + +--- + +### disableTypingEvents + +Disables the typing indicator for this composer. + +| | | +| --- | --- | +| Type | `boolean` | +| Default | `false` | + +--- + +### enterKeyBehavior + +Determines Enter key behavior. + +| | | +| --- | --- | +| Type | `EnterKeyBehavior` | +| Default | `EnterKeyBehavior.SendMessage` | + +```ts +enum EnterKeyBehavior { + SendMessage = "sendMessage", + NewLine = "newLine", + None = "none", } ``` - +--- - +### group -*** +The recipient group for the composer. -### Functionality +| | | +| --- | --- | +| Type | `CometChat.Group` | +| Default | `undefined` | -These are a set of small functional customizations that allow you to fine-tune the overall experience of the component. With these, you can change text, set custom icons, and toggle the visibility of UI elements. +--- - - -```tsx -import React from "react"; -import { CometChat } from "@cometchat/chat-sdk-javascript"; -import { CometChatMessageComposer } from "@cometchat/chat-uikit-react"; +### headerView -; -``` +Custom component displayed above the composer input. - +| | | +| --- | --- | +| Type | `JSX.Element` | +| Default | `undefined` | - +--- -Below is a list of customizations along with corresponding code snippets - -| Property | Description | Code | -| --------------------------------- | --------------------------------------------------------------------------------------- | ------------------------------------------------- | -| **Initial Composer Text** | The initial text pre-filled in the message input when the component mounts. | `initialComposerText="Hello"` | -| **Disable Typing Events** | Disables the typing indicator for the current message composer. | `disableTypingEvents={true}` | -| **Disable Mentions** | Disables the mentions functionality in the message composer. | `disableMentions={true}` | -| **Disable Mention All** | Controls whether group mentions like @all appear in suggestions. | `disableMentionAll={true}` | -| **Mention All Label** | Allows setting a custom alias label for group mentions (@channel, @everyone, etc.). | `mentionAllLabel="all"` | -| **Mentions Users Request Builder** | Provides a custom UsersRequestBuilder to control how the mentioned users list is fetched. | `mentionsUsersRequestBuilder={usersRequestBuilder}` | -| **Mentions Group Members Request Builder** | Provides a custom GroupMembersRequestBuilder to customize how mentioned group members are retrieved. | `mentionsGroupMembersRequestBuilder={groupMembersRequestBuilder}` | -| **Hide Image Attachment Option** | Hides the image attachment option in the message composer. | `hideImageAttachmentOption={true}` | -| **Hide Video Attachment Option** | Hides the video attachment option in the message composer. | `hideVideoAttachmentOption={true}` | -| **Hide Audio Attachment Option** | Hides the audio attachment option in the message composer. | `hideAudioAttachmentOption={true}` | -| **Hide File Attachment Option** | Hides the file attachment option in the message composer. | `hideFileAttachmentOption={true}` | -| **Hide Polls Option** | Hides the polls option in the message composer. | `hidePollsOption={true}` | -| **Hide Collaborative Document** | Hides the collaborative document option in the message composer. | `hideCollaborativeDocumentOption={true}` | -| **Hide Collaborative Whiteboard** | Hides the collaborative whiteboard option in the message composer. | `hideCollaborativeWhiteboardOption={true}` | -| **Hide Attachment Button** | Hides the attachment button in the message composer. | `hideAttachmentButton={true}` | -| **Hide Voice Recording Button** | Hides the voice recording button in the message composer. | `hideVoiceRecordingButton={true}` | -| **Hide Emoji Keyboard Button** | Hides the emoji keyboard button in the message composer. | `hideEmojiKeyboardButton={true}` | -| **Hide Stickers Button** | Hides the stickers button in the message composer. | `hideStickersButton={true}` | -| **Hide Send Button** | Hides the send button in the message composer. | `hideSendButton={true}` | -| **Show Scrollbar** | Controls the visibility of the scrollbar in the composer. | `showScrollbar={true}` | -| **User** | Specifies the recipient of the message (user object). | `user={chatUser}` | -| **Group** | Specifies the group to send messages to. Used if the `user` prop is not provided. | `group={chatGroup}` | -| **Parent Message ID** | Specifies the ID of the parent message for threading or replying to a specific message. | `parentMessageId={12345}` | -| **Enter Key Behavior** | Determines the behavior of the Enter key (e.g., send message or add a new line). | `enterKeyBehavior={EnterKeyBehavior.SendMessage}` | -| **Disable Sound for Message** | Disables sound for incoming messages. | `disableSoundForMessage={true}` | -| **Custom Sound for Message** | Specifies a custom audio sound for incoming messages. | `customSoundForMessage="sound.mp3"` | - -*** - -### Advanced - -For advanced-level customization, you can set custom views to the component. This lets you tailor each aspect of the component to fit your exact needs and application aesthetics. You can create and define your views, layouts, and UI elements and then incorporate those into the component. - -*** - -#### AttachmentOptions - -By using `attachmentOptions`, you can set a list of custom `MessageComposerActions` for the MessageComposer Component. This will override the existing list of `MessageComposerActions`. - -Shown below is the default chat interface. +### hideAttachmentButton - - - +Hides the entire attachment button. -The customized chat interface is displayed below. +| | | +| --- | --- | +| Type | `boolean` | +| Default | `false` | - - - +--- -Use the following code to achieve the customization shown above. +### hideAudioAttachmentOption - - -```tsx -import React from "react"; -import { CometChat } from "@cometchat/chat-sdk-javascript"; -import { - CometChatMessageComposer, - CometChatMessageComposerAction, -} from "@cometchat/chat-uikit-react"; +Hides the audio attachment option. -function getAttachments() { - return [ - new CometChatMessageComposerAction({ - id: "custom1", - title: "Custom Option 1", - iconURL: "Icon URL", - }), - new CometChatMessageComposerAction({ - id: "custom2", - title: "Custom Option 2", - iconURL: "Icon URL", - }), - new CometChatMessageComposerAction({ - id: "custom3", - title: "Custom Option 3", - iconURL: "Icon URL", - }), - new CometChatMessageComposerAction({ - id: "custom4", - title: "Custom Option 4", - iconURL: "Icon URL", - }), - ]; -} +| | | +| --- | --- | +| Type | `boolean` | +| Default | `false` | -; -``` +--- - +### hideCollaborativeDocumentOption - -```css -.cometchat-message-composer__secondary-button-view-attachment-button - .cometchat-action-sheet { - border: none; - border-radius: inherit; - background: transparent; - box-shadow: none; - width: 100%; -} +Hides the collaborative document option. -.cometchat-message-composer__secondary-button-view-attachment-button - .cometchat-popover__content - > .cometchat { - border-radius: inherit; -} +| | | +| --- | --- | +| Type | `boolean` | +| Default | `false` | -.cometchat-message-composer__secondary-button-view-attachment-button - .cometchat-popover__content { - height: 240px; -} +--- -.cometchat-message-composer__secondary-button-view-attachment-button - .cometchat-action-sheet__item-icon { - background: #141414; -} -``` +### hideCollaborativeWhiteboardOption - +Hides the collaborative whiteboard option. - +| | | +| --- | --- | +| Type | `boolean` | +| Default | `false` | -*** +--- -#### AuxiliaryButtonView +### hideEmojiKeyboardButton -You can insert a custom view into the MessageComposer component to add additional functionality using the following method. +Hides the emoji keyboard button. -Please note that the MessageComposer Component utilizes the AuxiliaryButton to provide sticker and AI functionality. Overriding the AuxiliaryButton will subsequently replace the sticker functionality. +| | | +| --- | --- | +| Type | `boolean` | +| Default | `false` | -Shown below is the default chat interface. +--- - - - +### hideFileAttachmentOption -The customized chat interface is displayed below. +Hides the file attachment option. - - - +| | | +| --- | --- | +| Type | `boolean` | +| Default | `false` | -Use the following code to achieve the customization shown above. +--- - - -```tsx -import React from "react"; -import { CometChat } from "@cometchat/chat-sdk-javascript"; -import { - CometChatMessageComposer, - IconStyle, - CometChatButton, -} from "@cometchat/chat-uikit-react"; +### hideImageAttachmentOption -const auxiliaryButtonView = ( - { - // logic here - }} - /> -); - -; -``` +Hides the image attachment option. - +| | | +| --- | --- | +| Type | `boolean` | +| Default | `false` | - +--- + +### hidePollsOption -*** +Hides the polls option. -#### SendButtonView +| | | +| --- | --- | +| Type | `boolean` | +| Default | `false` | -You can set a custom view in place of the already existing send button view. +--- -Shown below is the default chat interface. +### hideSendButton - - - +Hides the send button. -The customized chat interface is displayed below. +| | | +| --- | --- | +| Type | `boolean` | +| Default | `false` | - - - +--- -Use the following code to achieve the customization shown above. +### hideStickersButton - - -```tsx -import React from "react"; -import { CometChat } from "@cometchat/chat-sdk-javascript"; -import { - CometChatMessageComposer, - CometChatButton, -} from "@cometchat/chat-uikit-react"; +Hides the stickers button. -const sendButtonView = ( - { - // logic here - }} - /> -); +| | | +| --- | --- | +| Type | `boolean` | +| Default | `false` | -; -``` +--- - +### hideVideoAttachmentOption - -```css -.cometchat-message-composer - div:not([class]) - .message-composer__send-button - .cometchat-button { - background: #edeafa; -} +Hides the video attachment option. -.cometchat-message-composer - div:not([class]) - .message-composer__send-button - .cometchat-button__icon { - background: #6852d6; -} -``` +| | | +| --- | --- | +| Type | `boolean` | +| Default | `false` | - +--- - +### hideVoiceRecordingButton -*** +Hides the voice recording button. -#### HeaderView +| | | +| --- | --- | +| Type | `boolean` | +| Default | `false` | -You can set custom headerView to the MessageComposer component using the following method. +--- -Shown below is the default chat interface. +### initialComposerText - - - +Pre-fills the text input when the component mounts. -The customized chat interface is displayed below. +| | | +| --- | --- | +| Type | `string` | +| Default | `""` | - - - +--- -Use the following code to achieve the customization shown above. +### mentionAllLabel - - -```tsx -import React from "react"; -import { CometChat } from "@cometchat/chat-sdk-javascript"; -import { CometChatMessageComposer } from "@cometchat/chat-uikit-react"; +Custom alias label for group mentions. -const getHeaderView = () => { - return ( -
-
-
- User has paused their notifications -
-
- ); -}; +| | | +| --- | --- | +| Type | `string` | +| Default | `"all"` | -; -``` +--- -
+### mentionsGroupMembersRequestBuilder - -```css -.cometchat-message-composer .message-composer__header-view { - display: flex; - align-items: center; - align-content: center; - gap: 8px var(--cometchat-padding-2, 8px); - align-self: stretch; - flex-wrap: wrap; - width: 100%; -} +Custom builder to control how mentioned group members are fetched. -.cometchat-message-composer__header { - background: #dcd7f6; - border-radius: var(--cometchat-radius-ax, 1000px); - padding: var(--cometchat-padding-2, 8px) var(--cometchat-padding-5, 20px); -} +| | | +| --- | --- | +| Type | `CometChat.GroupMembersRequestBuilder` | +| Default | `undefined` | -.cometchat-message-composer - .message-composer__header-view - .message-composer__header-view-text { - overflow: hidden; - color: var(--cometchat-text-color-primary, #141414); - text-overflow: ellipsis; - font: var(--cometchat-font-body-regular); -} +--- -.cometchat-message-composer - .message-composer__header-view - .message-composer__header-view-icon { - display: flex; - width: 24px; - height: 24px; - justify-content: center; - align-items: center; - background: var(--cometchat-primary-color); - -webkit-mask: url("icon url") center center no-repeat; - -webkit-mask-size: contain; - mask: url("icon url") center center no-repeat; - mask-size: contain; -} -``` +### mentionsUsersRequestBuilder - +Custom builder to control how mentioned users are fetched. -
+| | | +| --- | --- | +| Type | `CometChat.UsersRequestBuilder` | +| Default | `undefined` | -*** +--- -#### TextFormatters +### onError -Assigns the list of text formatters. If the provided list is not null, it sets the list. Otherwise, it assigns the default text formatters retrieved from the data source. To configure the existing Mentions look and feel check out [CometChatMentionsFormatter](/ui-kit/react/mentions-formatter-guide) +Callback fired when the component encounters an error. - - -```ts -import { CometChatTextFormatter } from "@cometchat/chat-uikit-react"; -import DialogHelper from "./Dialog"; -import { CometChat } from "@cometchat/chat-sdk-javascript"; +| | | +| --- | --- | +| Type | `((error: CometChat.CometChatException) => void) \| null` | +| Default | `undefined` | -class ShortcutFormatter extends CometChatTextFormatter { - private shortcuts: { [key: string]: string } = {}; - private dialogIsOpen: boolean = false; - private dialogHelper = new DialogHelper(); - private currentShortcut: string | null = null; // Track the currently open shortcut - - constructor() { - super(); - this.setTrackingCharacter("!"); - CometChat.callExtension("message-shortcuts", "GET", "v1/fetch", undefined) - .then((data: any) => { - if (data && data.shortcuts) { - this.shortcuts = data.shortcuts; - } - }) - .catch((error) => console.log("error fetching shortcuts", error)); - } +--- - onKeyDown(event: KeyboardEvent) { - const caretPosition = - this.currentCaretPosition instanceof Selection - ? this.currentCaretPosition.anchorOffset - : 0; - const textBeforeCaret = this.getTextBeforeCaret(caretPosition); - - const match = textBeforeCaret.match(/!([a-zA-Z]+)$/); - if (match) { - const shortcut = match[0]; - const replacement = this.shortcuts[shortcut]; - if (replacement) { - // Close the currently open dialog, if any - if (this.dialogIsOpen && this.currentShortcut !== shortcut) { - this.closeDialog(); - } - this.openDialog(replacement, shortcut); - } - } - } +### onSendButtonClick - getCaretPosition() { - if (!this.currentCaretPosition?.rangeCount) return { x: 0, y: 0 }; - const range = this.currentCaretPosition?.getRangeAt(0); - const rect = range.getBoundingClientRect(); - return { - x: rect.left, - y: rect.top, - }; - } +Callback fired when the send button is clicked. Overrides default send behavior. - openDialog(buttonText: string, shortcut: string) { - this.dialogHelper.createDialog( - () => this.handleButtonClick(buttonText), - buttonText - ); - this.dialogIsOpen = true; - this.currentShortcut = shortcut; - } +| | | +| --- | --- | +| Type | `(message: CometChat.BaseMessage, previewMessageMode?: PreviewMessageMode) => void` | +| Default | `undefined` | - closeDialog() { - this.dialogHelper.closeDialog(); // Use DialogHelper to close the dialog - this.dialogIsOpen = false; - this.currentShortcut = null; - } +--- - handleButtonClick = (buttonText: string) => { - if (this.currentCaretPosition && this.currentRange) { - // Inserting the replacement text corresponding to the shortcut - const shortcut = Object.keys(this.shortcuts).find( - (key) => this.shortcuts[key] === buttonText - ); - if (shortcut) { - const replacement = this.shortcuts[shortcut]; - this.addAtCaretPosition( - replacement, - this.currentCaretPosition, - this.currentRange - ); - } - } - if (this.dialogIsOpen) { - this.closeDialog(); - } - }; +### onTextChange - getFormattedText(text: string): string { - return text; - } +Callback fired as the user types. - private getTextBeforeCaret(caretPosition: number): string { - if ( - this.currentRange && - this.currentRange.startContainer && - typeof this.currentRange.startContainer.textContent === "string" - ) { - const textContent = this.currentRange.startContainer.textContent; - if (textContent.length >= caretPosition) { - return textContent.substring(0, caretPosition); - } - } - return ""; - } -} +| | | +| --- | --- | +| Type | `(text: string) => void` | +| Default | `undefined` | -export default ShortcutFormatter; -``` +--- - +### parentMessageId - -```tsx -import React from "react"; -import ReactDOM from "react-dom"; +Targets a thread; messages sent as replies to this parent. -interface DialogProps { - onClick: () => void; - buttonText: string; -} +| | | +| --- | --- | +| Type | `number` | +| Default | `undefined` | -const Dialog: React.FC = ({ onClick, buttonText }) => { - return ( -
- -
- ); -}; +--- -export default class DialogHelper { - private dialogContainer: HTMLDivElement | null = null; +### placeholderText - createDialog(onClick: () => void, buttonText: string) { - this.dialogContainer = document.createElement("div"); - document.body.appendChild(this.dialogContainer); - ReactDOM.render( - , - this.dialogContainer - ); - } +Placeholder text displayed in the message input field when empty. - closeDialog() { - if (this.dialogContainer) { - ReactDOM.unmountComponentAtNode(this.dialogContainer); - this.dialogContainer.remove(); - this.dialogContainer = null; - } - } -} -``` +| | | +| --- | --- | +| Type | `string` | +| Default | `""` | -
+--- - -```tsx -import React from "react"; -import { CometChat } from "@cometchat/chat-sdk-javascript"; -import { CometChatMessageComposer } from "@cometchat/chat-uikit-react"; -import ShortcutFormatter from "./ShortCutFormatter"; - -export function MessageComposerDemo() { - const [chatUser, setChatUser] = React.useState(); - React.useEffect(() => { - CometChat.getUser("uid").then((user) => { - setChatUser(user); - }); - }, []); +### sendButtonView - return chatUser ? ( -
- -
- ) : null; -} -``` +Custom JSX replacing the send button. -
+| | | +| --- | --- | +| Type | `JSX.Element` | +| Default | Built-in send button | -
+--- + +### showScrollbar + +Shows the scrollbar in the composer input. + +| | | +| --- | --- | +| Type | `boolean` | +| Default | `false` | + +--- + +### textFormatters + +Custom text formatters for the composer input. + +| | | +| --- | --- | +| Type | `CometChatTextFormatter[]` | +| Default | Default formatters from data source | + +See [CometChatMentionsFormatter](/ui-kit/react/mentions-formatter-guide). + +--- + +### user + +The recipient user for the composer. + +| | | +| --- | --- | +| Type | `CometChat.User` | +| Default | `undefined` | + +--- + +## Events + +| Event | Payload | Fires when | +| --- | --- | --- | +| `CometChatMessageEvents.ccMessageSent` | `IMessages` | Message sent | +| `CometChatMessageEvents.ccMessageEdited` | `IMessages` | Message edited | +| `CometChatMessageEvents.ccReplyToMessage` | `IMessages` | User replies to message | + +--- -*** +## CSS Selectors + +| Target | Selector | +| --- | --- | +| Root | `.cometchat-message-composer` | +| Send button | `.cometchat-message-composer__send-button` | +| Send button active | `.cometchat-message-composer__send-button-active` | +| Sticker popover | `.cometchat-message-composer__auxilary-button-view-sticker-button .cometchat-popover__content` | +| Emoji keyboard popover | `.cometchat-message-composer__emoji-keyboard-button .cometchat-popover__content` | +| Attachment popover | `.cometchat-message-composer__secondary-button-view-attachment-button .cometchat-popover__content` | +| Voice recording popover | `.cometchat-message-composer__voice-recording-button .cometchat-popover__content` | +| Header area | `.cometchat-message-composer__header` | diff --git a/ui-kit/react/message-header.mdx b/ui-kit/react/message-header.mdx index 28d7d0c85..355d456cf 100644 --- a/ui-kit/react/message-header.mdx +++ b/ui-kit/react/message-header.mdx @@ -1,383 +1,328 @@ --- title: "Message Header" +description: "Toolbar displaying user/group avatar, name, status, typing indicator, back button, and call controls for a single conversation." --- + +```json +{ + "component": "CometChatMessageHeader", + "package": "@cometchat/chat-uikit-react", + "import": "import { CometChatMessageHeader } from \"@cometchat/chat-uikit-react\";", + "cssImport": "import \"@cometchat/chat-uikit-react/css-variables.css\";", + "description": "Toolbar displaying user/group avatar, name, status, typing indicator, back button, and call controls for a single conversation.", + "cssRootClass": ".cometchat-message-header", + "note": "View slots are JSX.Element (not functions) — unlike list components.", + "props": { + "data": { + "user": { "type": "CometChat.User", "default": "undefined" }, + "group": { "type": "CometChat.Group", "default": "undefined" }, + "lastActiveAtDateTimeFormat": { "type": "CalendarObject", "default": "component default" }, + "summaryGenerationMessageCount": { "type": "number", "default": 1000 } + }, + "callbacks": { + "onBack": "() => void", + "onError": "((error: CometChat.CometChatException) => void) | null", + "onItemClick": "() => void", + "onSearchOptionClicked": "() => void" + }, + "visibility": { + "showBackButton": { "type": "boolean", "default": false }, + "hideVideoCallButton": { "type": "boolean", "default": false }, + "hideVoiceCallButton": { "type": "boolean", "default": false }, + "hideUserStatus": { "type": "boolean", "default": false }, + "showConversationSummaryButton": { "type": "boolean", "default": false }, + "showSearchOption": { "type": "boolean", "default": false }, + "enableAutoSummaryGeneration": { "type": "boolean", "default": false } + }, + "viewSlots": { + "itemView": "JSX.Element", + "leadingView": "JSX.Element", + "titleView": "JSX.Element", + "subtitleView": "JSX.Element", + "trailingView": "JSX.Element", + "auxiliaryButtonView": "JSX.Element" + } + }, + "sdkListeners": [ + "onUserOnline", + "onUserOffline", + "onTypingStarted", + "onTypingEnded", + "onGroupMemberJoined", + "onGroupMemberLeft", + "onGroupMemberKicked", + "onGroupMemberBanned", + "onMemberAddedToGroup" + ], + "types": { + "CalendarObject": { + "today": "string | undefined", + "yesterday": "string | undefined", + "lastWeek": "string | undefined", + "otherDays": "string | undefined", + "relativeTime": { + "minute": "string | undefined", + "minutes": "string | undefined", + "hour": "string | undefined", + "hours": "string | undefined" + } + } + } +} +``` + -## Overview - -`MessageHeader` is a Component that showcases the [User](/sdk/javascript/users-overview) or [Group](/sdk/javascript/groups-overview) details in the toolbar. Furthermore, it also presents a typing indicator and a back navigation button for ease of use. - - - - - -The `MessageHeader` is comprised of the following components: - -| Component | Description | -| ----------------- | ---------------------------------------------------------------------------------------------------------------------------------------------- | -| CometChatListItem | This component’s view consists of avatar, status indicator , title, and subtitle. The fields are then mapped with the SDK’s user, group class. | -| Back Button | BackButton that allows users to navigate back from the current activity or screen to the previous one. | - -## Usage +## Where It Fits -### Integration +`CometChatMessageHeader` is a toolbar component that sits above `CometChatMessageList` and `CometChatMessageComposer`. It receives a `user` or `group` prop and displays the conversation's avatar, name, online status, and typing indicator. Call buttons are rendered automatically when the calling extension is enabled. - - ```tsx -import React from "react"; +import { useEffect, useState } from "react"; +import { + CometChatMessageHeader, + CometChatMessageList, + CometChatMessageComposer, +} from "@cometchat/chat-uikit-react"; import { CometChat } from "@cometchat/chat-sdk-javascript"; -import { CometChatMessageHeader } from "@cometchat/chat-uikit-react"; +import "@cometchat/chat-uikit-react/css-variables.css"; -export function MessageHeaderDemo() { - const [chatUser, setChatUser] = React.useState(); - React.useEffect(() => { - CometChat.getUser("uid").then((user) => { - setChatUser(user); - }); - }, []); +function ChatView() { + const [user, setUser] = useState(); - return chatUser ? ( -
{chatUser && }
- ) : null; -} -``` - -
+ useEffect(() => { + CometChat.getUser("UID").then(setUser); + }, []); - -```tsx -import { MessageHeaderDemo } from "./MessageHeaderDemo"; + if (!user) return null; -export default function App() { return ( -
-
- -
+
+ + +
); } ``` - - - - -### Actions - -[Actions](/ui-kit/react/components-overview#actions) dictate how a component functions. They are divided into two types: Predefined and User-defined. You can override either type, allowing you to tailor the behavior of the component to fit your specific needs. - -#### 1. OnBack - -`OnBack` is triggered when you click on the back button of the Message Header component. You can override this action using the following code snippet. + + + -**Example** +--- -In this example, we are employing the `onBack` action. +## Minimal Render - - ```tsx -import React from "react"; -import { CometChat } from "@cometchat/chat-sdk-javascript"; +import { useEffect, useState } from "react"; import { CometChatMessageHeader } from "@cometchat/chat-uikit-react"; +import { CometChat } from "@cometchat/chat-sdk-javascript"; +import "@cometchat/chat-uikit-react/css-variables.css"; -export function MessageHeaderDemo() { - const [chatUser, setChatUser] = React.useState(); - React.useEffect(() => { - CometChat.getUser("uid").then((user) => { - setChatUser(user); - }); - }, []); +function MessageHeaderDemo() { + const [user, setUser] = useState(); - function handleOnBack() { - console.log("your custom on back action"); - } + useEffect(() => { + CometChat.getUser("UID").then(setUser); + }, []); - return chatUser ? ( -
- {chatUser && ( - - )} -
- ) : null; + return user ? : null; } -``` -
+export default MessageHeaderDemo; +``` -
+Root CSS class: `.cometchat-message-header` -*** +--- -#### 2. OnError +## Actions and Events -This action doesn't change the behavior of the component but rather listens for any errors that occur in the Message Header component. +### Callback Props -**Example** +#### onBack -In this example, we are employing the `onError` action. +Fires when the back button is clicked. Requires `showBackButton={true}`. - - ```tsx -import React from "react"; -import { CometChat } from "@cometchat/chat-sdk-javascript"; import { CometChatMessageHeader } from "@cometchat/chat-uikit-react"; +import { CometChat } from "@cometchat/chat-sdk-javascript"; -export function MessageHeaderDemo() { - const [chatUser, setChatUser] = React.useState(); - React.useEffect(() => { - CometChat.getUser("uid").then((user) => { - setChatUser(user); - }); - }, []); - - function handleError(error: CometChat.CometChatException) { - throw new Error("your custom error action"); - } - return chatUser ? ( -
- {chatUser && ( - - )} -
- ) : null; +function HeaderWithBack({ user }: { user: CometChat.User }) { + return ( + console.log("Navigate back")} + /> + ); } ``` -
+#### onItemClick -
+Fires when the header list item area (avatar + name) is clicked. -*** - -##### 3. onSearchOptionClicked - -The `onSearchOptionClicked` event is triggered when the user clicks the search option. It does not have a default behavior. However, you can override its behavior using the following code snippet. - - - ```tsx import { CometChatMessageHeader } from "@cometchat/chat-uikit-react"; +import { CometChat } from "@cometchat/chat-sdk-javascript"; -const handleSearchClick = () => { - console.log("Search option clicked"); -}; - -; +function HeaderWithItemClick({ user }: { user: CometChat.User }) { + return ( + console.log("Open user detail")} + /> + ); +} ``` - - - +#### onSearchOptionClicked -*** +Fires when the search option is clicked. Requires `showSearchOption={true}`. -#### 4. OnItemClick - -`OnItemClick` is triggered when you click on a ListItem of the `CometChatMessageHeader` component. The `OnItemClick` action doesn't have a predefined behavior. You can override this action using the following code snippet. - - - ```tsx -import { MessageHeaderDemo } from "@cometchat/chat-uikit-react"; - -const getOnItemClick = () => { - console.log("List item clicked"); -}; +import { CometChatMessageHeader } from "@cometchat/chat-uikit-react"; +import { CometChat } from "@cometchat/chat-sdk-javascript"; -; +function HeaderWithSearch({ user }: { user: CometChat.User }) { + return ( + console.log("Open search")} + /> + ); +} ``` - - - - -*** - -### Filters - -**Filters** allow you to customize the data displayed in a list within a `Component`. You can filter the list based on your specific criteria, allowing for a more customized. Filters can be applied using `RequestBuilders` of Chat SDK. - -The `MessageHeader` component does not have any exposed filters. - -### Events - -[Events](/ui-kit/react/components-overview#events) are emitted by a `Component`. By using event you can extend existing functionality. Being global events, they can be applied in Multiple Locations and are capable of being Added or Removed. +#### onError -The `MessageHeader` component does not produce any events. +Fires on internal errors. -## Customization - -To fit your app's design requirements, you can customize the appearance of the Message Header component. We provide exposed methods that allow you to modify the experience and behavior according to your specific needs. - -### Style - -To customize the appearance, you can customise css of `CometChatMessageHeader` - -**Example** - - - - - - - -```ts -import React from "react"; -import { CometChat } from "@cometchat/chat-sdk-javascript"; +```tsx import { CometChatMessageHeader } from "@cometchat/chat-uikit-react"; +import { CometChat } from "@cometchat/chat-sdk-javascript"; -// Assuming groupObj is defined elsewhere in your code -; -``` - - - - -```css -.cometchat-message-header .cometchat-list-item .cometchat-avatar { - background: #f0999b; - border-radius: 8px; -} -.cometchat-message-header .cometchat-avatar__text { - font-family: "SF Pro"; +function HeaderWithError({ user }: { user: CometChat.User }) { + return ( + { + console.error("MessageHeader error:", error); + }} + /> + ); } ``` - - - - -### Functionality +### SDK Events (Real-Time, Automatic) -These are a set of small functional customizations that allow you to fine-tune the overall experience of the component. With these, you can change text, set custom icons, and toggle the visibility of UI elements. +The component listens to these SDK events internally. No manual attachment needed. -Here is a code snippet demonstrating how you can customize the functionality of the Message Header component. - - - -```ts -import { CometChatMessageHeader } from "@cometchat/chat-uikit-react"; - -; -``` +| SDK Listener | Internal behavior | +| --- | --- | +| `onUserOnline` / `onUserOffline` | Updates the user's online/offline status indicator | +| `onTypingStarted` / `onTypingEnded` | Shows/hides the typing indicator in the subtitle area | +| Group member events | Updates group member count when members join/leave | - - - + +In React 18 StrictMode, `useEffect` runs twice on mount in development. The component handles listener cleanup internally. + -Following is a list of customizations along with their corresponding code snippets: +--- -| Property | Description | Code | -| ------------------------------------ | --------------------------------------------------------------------------------------------------- | -------------------------------------- | -| **Show Back Button** | Shows the back button. | `showBackButton={true}` | -| **Hide Video Call Button** | Hides the video call button. | `hideVideoCallButton={true}` | -| **Hide Voice Call Button** | Hides the voice call button. | `hideVoiceCallButton={true}` | -| **Show Conversation Summary Button** | Shows the conversation summary button. | `showConversationSummaryButton={true}` | -| **Hide User Status** | Hides the user's online/offline status indicator. | `hideUserStatus={true}` | -| **Show Search Option** | Shows the search option. | `showSearchOption={true}` | -| **User** | A `CometChat.User` object representing the user whose information (e.g., status) is displayed. | `user={chatUser}` | -| **Group** | A `CometChat.Group` object representing the group whose details (e.g., member count) are displayed. | `group={chatGroup}` | -| **Summary Generation Message Count** | Number of messages for which the summary should be shown. | `summaryGenerationMessageCount={1000}` | -| **Disable Auto Summary Generation** | Disables the auto generation of conversation summary. | `disableAutoSummaryGeneration={true}` | +## Custom View Slots -### Advanced +View slots for `CometChatMessageHeader` are `JSX.Element` (not functions) — unlike list components where slots receive a data parameter. -For advanced-level customization, you can set custom views to the component. This lets you tailor each aspect of the component to fit your exact needs and application aesthetics. You can create and define your views, layouts, and UI elements and then incorporate those into the component. +| Slot | Type | Replaces | +| --- | --- | --- | +| `itemView` | `JSX.Element` | Entire list item (avatar + name + subtitle) | +| `leadingView` | `JSX.Element` | Avatar / left section | +| `titleView` | `JSX.Element` | Name / title text | +| `subtitleView` | `JSX.Element` | Subtitle text (status / typing indicator) | +| `trailingView` | `JSX.Element` | Right section (call buttons area) | +| `auxiliaryButtonView` | `JSX.Element` | Auxiliary button area (next to call buttons) | -#### ItemView +### itemView -The customized chat interface is displayed below. +Replace the entire list item (avatar + name + subtitle). -Use the following code to achieve the customization shown above. - -```ts -import React from "react"; -import { CometChat } from "@cometchat/chat-sdk-javascript"; +```tsx import { CometChatMessageHeader, CometChatListItem, } from "@cometchat/chat-uikit-react"; +import { CometChat } from "@cometchat/chat-sdk-javascript"; -// Custom list item view definition -const CustomItemView = ( - <> - + } + showBackButton={true} /> - -); - -; + ); +} ``` - - - + ```css .cometchat-message-header .cometchat-list-item .cometchat-avatar { border-radius: 8px; } ``` - - -*** - -#### TitleView +### titleView -The customized chat interface is displayed below. +Replace the name / title text. -Use the following code to achieve the customization shown above. - -```ts -import React from "react"; -import { CometChat } from "@cometchat/chat-sdk-javascript"; +```tsx import { CometChatMessageHeader } from "@cometchat/chat-uikit-react"; +import { CometChat } from "@cometchat/chat-sdk-javascript"; -// Custom title view component -function CustomTitleView() { +function CustomTitleHeader({ user }: { user: CometChat.User }) { return ( -
- - {userObj.getName() + " • "} - - - {userObj.getStatusMessage()} - -
+ + + {user.getName() + " • "} + + + {user.getStatusMessage()} + +
+ } + /> ); } - -; ``` -
- - + ```css .cometchat-message-header .message-header__title-view { display: flex; @@ -385,106 +330,80 @@ function CustomTitleView() { width: 100%; } -.cometchat-message-header - .message-header__title-view - .message-header__title-view-name { +.message-header__title-view-name { color: #141414; font: 500 16px/19.2px Roboto; - text-align: left; } -.cometchat-message-header - .message-header__title-view - .message-header__title-view-status { + +.message-header__title-view-status { color: #6852d6; font: 400 16px/19.2px Roboto; - text-align: left; } ``` - -
-*** - -#### SubtitleView +### subtitleView -The customized chat interface is displayed below. +Replace the subtitle text (status / typing indicator area). -Use the following code to achieve the customization shown above. - - - -```ts -import React from "react"; -import { CometChat } from "@cometchat/chat-sdk-javascript"; +```tsx import { CometChatMessageHeader } from "@cometchat/chat-uikit-react"; +import { CometChat } from "@cometchat/chat-sdk-javascript"; -// Custom subtitle view component -function CustomSubtitleView() { - return <>{group?.getMembersCount() + " • " + group?.getDescription()}; +function CustomSubtitleHeader({ group }: { group: CometChat.Group }) { + return ( + {group.getMembersCount() + " • " + group.getDescription()} + } + /> + ); } - -; ``` - - - - -*** +### leadingView -#### LeadingView - -The customized chat interface is displayed below. +Replace the avatar / left section. -Use the following code to achieve the customization shown above. - -```ts -import React from "react"; -import { CometChat } from "@cometchat/chat-sdk-javascript"; +```tsx import { CometChatMessageHeader, CometChatAvatar, } from "@cometchat/chat-uikit-react"; +import { CometChat } from "@cometchat/chat-sdk-javascript"; -// Custom title view component -function CustomLeadingView() { +function CustomLeadingHeader({ user }: { user: CometChat.User }) { return ( -
- - - ⭐ {userObj?.getRole()} - -
+ + + + {user.getRole()} + +
+ } + /> ); } - -; ``` -
- - + ```css -.cometchat-message-header - .cometchat-list-item - .message-header__leading-view - .cometchat-avatar__image, -.cometchat-message-header - .cometchat-list-item - .message-header__leading-view - .cometchat-avatar { +.cometchat-message-header .message-header__leading-view .cometchat-avatar { border-radius: 8px; height: 48px; width: 48px; @@ -503,203 +422,488 @@ function CustomLeadingView() { position: absolute; bottom: -2px; } + .message-header__leading-view { position: relative; } ``` - - -*** +### trailingView -#### TrailingView - -The customized chat interface is displayed below. +Replace the right section (call buttons area). -Use the following code to achieve the customization shown above. - - - -```ts -import React from "react"; -import { CometChat } from "@cometchat/chat-sdk-javascript"; +```tsx import { CometChatMessageHeader, CometChatButton, } from "@cometchat/chat-uikit-react"; +import { CometChat } from "@cometchat/chat-sdk-javascript"; -// Custom trailing view component -function CustomTrailingButtonView() { +function CustomTrailingHeader({ user }: { user: CometChat.User }) { return ( - <> - { - // Your logic here - }} - iconURL={icon} // Ensure `icon` is defined or passed as a prop - /> - + { /* custom action */ }} /> + } + /> ); } - -; ``` - +### auxiliaryButtonView - -```css -.cometchat-message-header - .cometchat-list-item__trailing-view - .cometchat-button { - background: transparent; - height: 24px; - width: 24px; - padding: 0; +Replace the auxiliary button area (next to call buttons). + + + + + +```tsx +import { + CometChatMessageHeader, + CometChatButton, +} from "@cometchat/chat-uikit-react"; +import { CometChat } from "@cometchat/chat-sdk-javascript"; + +function AuxiliaryButtonHeader({ group }: { group: CometChat.Group }) { + return ( + { /* custom action */ }} /> + } + /> + ); } +``` + +### lastActiveAtDateTimeFormat + +Customize the "last seen" timestamp format using a `CalendarObject`. + +```tsx +import { + CometChatMessageHeader, + CalendarObject, +} from "@cometchat/chat-uikit-react"; +import { CometChat } from "@cometchat/chat-sdk-javascript"; -.cometchat-message-header - .cometchat-list-item__trailing-view - .cometchat-button__icon { - background: black; +function CustomDateHeader({ user }: { user: CometChat.User }) { + const dateFormat = new CalendarObject({ + today: "hh:mm A", + yesterday: "[yesterday]", + otherDays: "DD MM YYYY", + }); + + return ( + + ); } ``` - + +If no property is passed in the [CalendarObject](/ui-kit/react/localize#calendarobject), the component checks the [global configuration](/ui-kit/react/localize#customisation) first. If also missing there, the component's default formatting applies. + - +--- -*** +## Common Patterns -#### AuxiliaryButtonView +### Header with back button and search -The customized chat interface is displayed below. +```tsx +import { CometChatMessageHeader } from "@cometchat/chat-uikit-react"; +import { CometChat } from "@cometchat/chat-sdk-javascript"; - - - +function FullFeaturedHeader({ user }: { user: CometChat.User }) { + return ( + { /* navigate back */ }} + onSearchOptionClicked={() => { /* open search */ }} + /> + ); +} +``` -Use the following code to achieve the customization shown above. +### Hide call buttons - - -```ts -import React from "react"; +```tsx +import { CometChatMessageHeader } from "@cometchat/chat-uikit-react"; import { CometChat } from "@cometchat/chat-sdk-javascript"; -import { - CometChatMessageHeader, - CometChatButton, -} from "@cometchat/chat-uikit-react"; -// Custom auxiliary view component -function CustomAuxiliaryButtonView() { +function NoCalls({ user }: { user: CometChat.User }) { return ( - <> - { - // Your logic here - }} - iconURL={icon} // Ensure `icon` is defined or passed as a prop - /> - + ); } +``` + +### Group header with AI summary -; +```tsx +import { CometChatMessageHeader } from "@cometchat/chat-uikit-react"; +import { CometChat } from "@cometchat/chat-sdk-javascript"; + +function GroupHeaderWithSummary({ group }: { group: CometChat.Group }) { + return ( + + ); +} ``` - +--- + +## CSS Architecture + +The component uses CSS custom properties (design tokens) defined in `@cometchat/chat-uikit-react/css-variables.css`. The cascade: + +1. Global tokens are set on the `.cometchat` root wrapper. +2. Component CSS (`.cometchat-message-header`) consumes these tokens via `var()` with fallback values. +3. Overrides target `.cometchat-message-header` descendant selectors in a global stylesheet. + +### Key Selectors + +| Target | Selector | +| --- | --- | +| Root | `.cometchat-message-header` | +| List item | `.cometchat-message-header .cometchat-list-item` | +| Body title | `.cometchat-message-header .cometchat-list-item__body-title` | +| Avatar | `.cometchat-message-header .cometchat-list-item .cometchat-avatar` | +| Leading view | `.cometchat-message-header .cometchat-list-item__leading-view` | +| Trailing view | `.cometchat-message-header .cometchat-list-item__trailing-view` | +| Subtitle | `.cometchat-message-header__subtitle` | +| Subtitle (typing) | `.cometchat-message-header__subtitle-typing` | +| Back button | `.cometchat-message-header__back-button` | +| Auxiliary button view | `.cometchat-message-header__auxiliary-button-view` | +| List item container | `.cometchat-message-header__listitem` | +| Title container | `.cometchat-message-header .cometchat-list-item__title-container` | + +### Example: Brand-themed header + + + + - ```css -.cometchat-message-header - .cometchat-message-header__auxiliary-view - .cometchat-button { - background: transparent; - height: 24px; - width: 24px; - padding: 0; +.cometchat-message-header .cometchat-list-item .cometchat-avatar { + background: #f0999b; + border-radius: 8px; } -.cometchat-message-header - .cometchat-message-header__auxiliary-view - .cometchat-button__icon { - background: black; +.cometchat-message-header .cometchat-avatar__text { + font-family: "SF Pro"; } ``` - +### Customization Matrix - +| What to change | Where | Property/API | Example | +| --- | --- | --- | --- | +| Override behavior on user interaction | Component props | `on` callbacks | `onBack={() => navigate(-1)}` | +| Toggle visibility of UI elements | Component props | `hide` / `show` boolean props | `hideVideoCallButton={true}` | +| Replace a section of the header | Component props | `View` JSX.Element props | `titleView={
Custom
}` | +| Change colors, fonts, spacing | Global CSS | Target `.cometchat-message-header` class | `.cometchat-message-header .cometchat-avatar { border-radius: 8px; }` | -#### LastActiveAt Date Time Format +--- -The `lastActiveAtDateTimeFormat` property allows you to customize the **last active** timestamp displayed in the message header. +## Accessibility -Default Date Time Format: +The component renders a toolbar with interactive elements. The back button, call buttons, and auxiliary buttons are keyboard-focusable and activate on Enter/Space. The avatar includes alt text. The typing indicator updates the subtitle text dynamically — screen readers announce the change via live region behavior. -```ruby -new CalendarObject({ - today: `[Last seen DD MMM at] hh:mm A`, // Example: "today at 10:30 AM" - yesterday: `[Last seen DD MMM at] hh:mm A`, // Example: "yesterday at 08:15 PM" - otherDays: `[Last seen DD MMM at] hh:mm A`, // Example: "25, Jan 05:45 PM" - relativeTime: { - hour: `Last seen %d hour ago`, // Example: "1 hour ago" - minute: `Last seen %d minute ago`, // Example: "1 minute ago" - minutes: `Last seen %d minutes ago`, // Example: "5 minutes ago" - }, -}); -``` +--- -The following example demonstrates how to modify the **last active** timestamp format using a custom [`CalendarObject`](/ui-kit/react/localize#calendarobject). +--- - - -```ts -import { - CometChatMessageHeader, - CalendarObject, -} from "@cometchat/chat-uikit-react"; +## Props -// Define a custom date format pattern -function getDateFormat() { - const dateFormat = new CalendarObject({ - today: `hh:mm A`, // Example: "10:30 AM" - yesterday: `[yesterday]`, // Example: "yesterday" - otherDays: `DD MM YYYY`, // Example: "25 01 2025" - }); - return dateFormat; -} +All props are optional unless noted otherwise. -// Apply the custom format to the CometChatMessageHeader component -; -``` +--- - +### auxiliaryButtonView - +Custom component for the auxiliary button area. - +| | | +| --- | --- | +| Type | `JSX.Element` | +| Default | `undefined` | -**Fallback Mechanism** +--- -* If you **do not** pass any property in the [**CalendarObject**](/ui-kit/react/localize#calendarobject), the component will first check the [**global configuration**](/ui-kit/react/localize#customisation). If the property is **also missing in the global configuration**, it will **fallback to the component's default formatting**. +### enableAutoSummaryGeneration - +Enables automatic conversation summary generation. + +| | | +| --- | --- | +| Type | `boolean` | +| Default | `false` | + +--- + +### group + +Displays group details in the header. + +| | | +| --- | --- | +| Type | `CometChat.Group` | +| Default | `undefined` | + +Pass either `user` or `group`, not both. + +--- + +### hideBackButton + +Hides the back navigation button. Deprecated — use `showBackButton` instead. + +| | | +| --- | --- | +| Type | `boolean` | +| Default | `true` | + +--- + +### hideUserStatus + +Hides the user's online/offline status indicator. + +| | | +| --- | --- | +| Type | `boolean` | +| Default | `false` | + +--- + +### hideVideoCallButton + +Hides the video call button. + +| | | +| --- | --- | +| Type | `boolean` | +| Default | `false` | + +--- + +### hideVoiceCallButton + +Hides the voice call button. + +| | | +| --- | --- | +| Type | `boolean` | +| Default | `false` | + +--- + +### itemView + +Custom component for the entire list item. + +| | | +| --- | --- | +| Type | `JSX.Element` | +| Default | `undefined` | + +--- + +### lastActiveAtDateTimeFormat + +Format for displaying the "last seen" timestamp. + +| | | +| --- | --- | +| Type | `CalendarObject` | +| Default | Component default | + +--- + +### leadingView + +Custom component for the avatar / left section. + +| | | +| --- | --- | +| Type | `JSX.Element` | +| Default | `undefined` | + +--- + +### onBack + +Callback fired when the back button is clicked. + +| | | +| --- | --- | +| Type | `() => void` | +| Default | `() => {}` | + +--- + +### onError + +Callback fired when the component encounters an error. + +| | | +| --- | --- | +| Type | `((error: CometChat.CometChatException) => void) \| null` | +| Default | `undefined` | + +--- + +### onItemClick + +Callback fired when the header list item is clicked. + +| | | +| --- | --- | +| Type | `() => void` | +| Default | `() => {}` | + +--- + +### onSearchOptionClicked + +Callback fired when the search option is clicked. + +| | | +| --- | --- | +| Type | `() => void` | +| Default | `() => {}` | + +--- + +### showBackButton + +Shows the back navigation button. + +| | | +| --- | --- | +| Type | `boolean` | +| Default | `false` | + +--- + +### showConversationSummaryButton + +Shows the AI conversation summary button. + +| | | +| --- | --- | +| Type | `boolean` | +| Default | `false` | + +--- + +### showSearchOption + +Shows the search option in the header. + +| | | +| --- | --- | +| Type | `boolean` | +| Default | `false` | + +--- + +### subtitleView + +Custom component for the subtitle text. + +| | | +| --- | --- | +| Type | `JSX.Element` | +| Default | `undefined` | + +--- + +### summaryGenerationMessageCount + +Number of messages used for AI summary generation. + +| | | +| --- | --- | +| Type | `number` | +| Default | `1000` | + +--- + +### titleView + +Custom component for the name / title text. + +| | | +| --- | --- | +| Type | `JSX.Element` | +| Default | `undefined` | + +--- + +### trailingView + +Custom component for the right section. + +| | | +| --- | --- | +| Type | `JSX.Element` | +| Default | `undefined` | + +--- + +### user + +Displays user details in the header. + +| | | +| --- | --- | +| Type | `CometChat.User` | +| Default | `undefined` | + +Pass either `user` or `group`, not both. + +--- -*** +## CSS Selectors + +| Target | Selector | +| --- | --- | +| Root | `.cometchat-message-header` | +| List item | `.cometchat-message-header .cometchat-list-item` | +| Body title | `.cometchat-message-header .cometchat-list-item__body-title` | +| Avatar | `.cometchat-message-header .cometchat-list-item .cometchat-avatar` | +| Leading view | `.cometchat-message-header .cometchat-list-item__leading-view` | +| Trailing view | `.cometchat-message-header .cometchat-list-item__trailing-view` | +| Subtitle | `.cometchat-message-header__subtitle` | +| Subtitle (typing) | `.cometchat-message-header__subtitle-typing` | +| Back button | `.cometchat-message-header__back-button` | +| Auxiliary button view | `.cometchat-message-header__auxiliary-button-view` | +| List item container | `.cometchat-message-header__listitem` | +| Title container | `.cometchat-message-header .cometchat-list-item__title-container` | +| Summary button | `.cometchat-message-header__conversation-summary-button` | +| Search button | `.cometchat-message-header__search-button` | +| Menu | `.cometchat-message-header__menu` | diff --git a/ui-kit/react/message-list.mdx b/ui-kit/react/message-list.mdx index e2300b1d1..5355782b7 100644 --- a/ui-kit/react/message-list.mdx +++ b/ui-kit/react/message-list.mdx @@ -1,1585 +1,1293 @@ --- title: "Message List" +description: "Scrollable list of sent and received messages with text, media, reactions, read receipts, threaded replies, and AI features." --- + +```json +{ + "component": "CometChatMessageList", + "package": "@cometchat/chat-uikit-react", + "import": "import { CometChatMessageList } from \"@cometchat/chat-uikit-react\";", + "cssImport": "import \"@cometchat/chat-uikit-react/css-variables.css\";", + "description": "Scrollable list of sent and received messages with text, media, reactions, read receipts, threaded replies, and AI features.", + "cssRootClass": ".cometchat-message-list", + "primaryOutput": { + "prop": "onThreadRepliesClick", + "type": "(message: CometChat.BaseMessage) => void" + }, + "props": { + "data": { + "user": { "type": "CometChat.User", "default": "undefined" }, + "group": { "type": "CometChat.Group", "default": "undefined" }, + "messagesRequestBuilder": { "type": "CometChat.MessagesRequestBuilder", "default": "SDK default" }, + "reactionsRequestBuilder": { "type": "CometChat.ReactionsRequestBuilder", "default": "undefined" }, + "parentMessageId": { "type": "number", "default": "undefined" }, + "templates": { "type": "CometChatMessageTemplate[]", "default": "SDK defaults" }, + "goToMessageId": { "type": "string", "default": "undefined" } + }, + "callbacks": { + "onThreadRepliesClick": "(message: CometChat.BaseMessage) => void", + "onReactionClick": "(reaction: CometChat.ReactionCount, message: CometChat.BaseMessage) => void", + "onReactionListItemClick": "(reaction: CometChat.Reaction, message: CometChat.BaseMessage) => void", + "onError": "((error: CometChat.CometChatException) => void) | null" + }, + "visibility": { + "hideDateSeparator": { "type": "boolean", "default": false }, + "hideStickyDate": { "type": "boolean", "default": false }, + "hideReceipts": { "type": "boolean", "default": false }, + "hideError": { "type": "boolean", "default": false }, + "hideReplyInThreadOption": { "type": "boolean", "default": false }, + "hideReplyOption": { "type": "boolean", "default": false }, + "hideTranslateMessageOption": { "type": "boolean", "default": false }, + "hideEditMessageOption": { "type": "boolean", "default": false }, + "hideDeleteMessageOption": { "type": "boolean", "default": false }, + "hideReactionOption": { "type": "boolean", "default": false }, + "hideMessagePrivatelyOption": { "type": "boolean", "default": false }, + "hideCopyMessageOption": { "type": "boolean", "default": false }, + "hideMessageInfoOption": { "type": "boolean", "default": false }, + "hideAvatar": { "type": "boolean", "default": false }, + "hideGroupActionMessages": { "type": "boolean", "default": false }, + "hideModerationView": { "type": "boolean", "default": false }, + "hideFlagMessageOption": { "type": "boolean", "default": false }, + "hideFlagRemarkField": { "type": "boolean", "default": false }, + "showConversationStarters": { "type": "boolean", "default": false }, + "showSmartReplies": { "type": "boolean", "default": false }, + "showMarkAsUnreadOption": { "type": "boolean", "default": false }, + "showScrollbar": { "type": "boolean", "default": false } + }, + "behavior": { + "messageAlignment": { "type": "MessageListAlignment", "default": "MessageListAlignment.standard" }, + "scrollToBottomOnNewMessages": { "type": "boolean", "default": false }, + "quickOptionsCount": { "type": "number", "default": 3 }, + "startFromUnreadMessages": { "type": "boolean", "default": false }, + "isAgentChat": { "type": "boolean", "default": false }, + "loadLastAgentConversation": { "type": "boolean", "default": false } + }, + "sound": { + "disableSoundForMessages": { "type": "boolean", "default": true }, + "customSoundForMessages": { "type": "string", "default": "undefined" } + }, + "ai": { + "smartRepliesKeywords": { "type": "string[]", "default": "[\"what\",\"when\",\"why\",\"who\",\"where\",\"how\",\"?\"]" }, + "smartRepliesDelayDuration": { "type": "number", "default": 10000 } + }, + "dateFormatting": { + "separatorDateTimeFormat": "CalendarObject", + "stickyDateTimeFormat": "CalendarObject", + "messageSentAtDateTimeFormat": "CalendarObject", + "messageInfoDateTimeFormat": "CalendarObject" + }, + "viewSlots": { + "headerView": "JSX.Element", + "footerView": "JSX.Element", + "loadingView": "JSX.Element", + "emptyView": "JSX.Element", + "errorView": "JSX.Element" + }, + "formatting": { + "textFormatters": { "type": "CometChatTextFormatter[]", "default": "default formatters" } + } + }, + "events": [ + { "name": "CometChatMessageEvents.ccMessageEdited", "payload": "IMessages" }, + { "name": "CometChatMessageEvents.ccMessageDeleted", "payload": "CometChat.BaseMessage" }, + { "name": "CometChatMessageEvents.ccMessageRead", "payload": "CometChat.BaseMessage" }, + { "name": "CometChatMessageEvents.ccReplyToMessage", "payload": "IMessages" }, + { "name": "CometChatUIEvents.ccOpenChat", "payload": "IOpenChat" }, + { "name": "CometChatUIEvents.ccActiveChatChanged", "payload": "IActiveChatChanged" } + ], + "sdkListeners": [ + "onTextMessageReceived", "onMediaMessageReceived", "onCustomMessageReceived", + "onMessageEdited", "onMessageDeleted", "onMessageModerated", + "onTypingStarted", "onTypingEnded", + "onMessagesDelivered", "onMessagesRead", "onMessagesDeliveredToAll", "onMessagesReadByAll" + ], + "types": { + "MessageListAlignment": { "left": 0, "standard": 1 }, + "CalendarObject": { "today": "string", "yesterday": "string", "lastWeek": "string", "otherDays": "string" } + } +} +``` + + +## Where It Fits + +`CometChatMessageList` renders a scrollable, real-time message feed for a user or group conversation. Wire it alongside `CometChatMessageHeader` and `CometChatMessageComposer` to build a standard chat view. + +```tsx +import { useState, useEffect } from "react"; +import { CometChat } from "@cometchat/chat-sdk-javascript"; +import { + CometChatMessageHeader, + CometChatMessageList, + CometChatMessageComposer, +} from "@cometchat/chat-uikit-react"; +import "@cometchat/chat-uikit-react/css-variables.css"; + +function ChatView() { + const [chatUser, setChatUser] = useState(); -## Overview + useEffect(() => { + CometChat.getUser("uid").then((user) => setChatUser(user)); + }, []); -`MessageList` is a composite component that displays a list of messages and effectively manages real-time operations. It includes various types of messages such as Text Messages, Media Messages, Stickers, and more. + return chatUser ? ( +
+ + + +
+ ) : null; +} +``` -*** - -## Usage - -### Integration +--- -The following code snippet illustrates how you can directly incorporate the MessageList component into your Application. +## Minimal Render - - ```tsx -import React from "react"; +import { useState, useEffect } from "react"; import { CometChat } from "@cometchat/chat-sdk-javascript"; import { CometChatMessageList } from "@cometchat/chat-uikit-react"; +import "@cometchat/chat-uikit-react/css-variables.css"; -export function MessageListDemo() { - const [chatUser, setChatUser] = React.useState(); - React.useEffect(() => { - CometChat.getUser("uid").then((user) => { - setChatUser(user); - }); +function MessageListDemo() { + const [chatUser, setChatUser] = useState(); + + useEffect(() => { + CometChat.getUser("uid").then((user) => setChatUser(user)); }, []); - return chatUser ? ( -
- -
- ) : null; + return chatUser ? : null; } + +export default MessageListDemo; ``` -
+Root CSS class: `.cometchat-message-list` + +--- + +## Filtering Messages + +Pass a `CometChat.MessagesRequestBuilder` to `messagesRequestBuilder`. The `UID`/`GUID` parameters are always overridden internally based on the `user`/`group` prop. - ```tsx -import { MessageListDemo } from "./MessageListDemo"; +import { CometChat } from "@cometchat/chat-sdk-javascript"; +import { CometChatMessageList } from "@cometchat/chat-uikit-react"; -export default function App() { +function FilteredMessageList() { return ( -
-
- -
-
+ ); } ``` -
- -
+### Reactions Request Builder - +```tsx +import { CometChat } from "@cometchat/chat-sdk-javascript"; +import { CometChatMessageList } from "@cometchat/chat-uikit-react"; -To fetch messages for a specific entity, you need to supplement it with `User` or `Group` Object. +function ReactionsFilteredList() { + return ( + + ); +} +``` - +Refer to [MessagesRequestBuilder](/sdk/javascript/additional-message-filtering) for the full builder API. -*** +--- -### Actions +## Actions and Events -[Actions](/ui-kit/react/components-overview#actions) dictate how a component functions. They are divided into two types: Predefined and User-defined. You can override either type, allowing you to tailor the behavior of the component to fit your specific needs. +### Callback Props -##### 1. onThreadRepliesClick +#### onThreadRepliesClick -`onThreadRepliesClick` is triggered when you click on the threaded message bubble. The `onThreadRepliesClick` action doesn't have a predefined behavior. You can override this action using the following code snippet. +Fires when a threaded message reply count is clicked. - - -```ts -import React from "react"; -import { CometChat } from "@cometchat/chat-sdk-javascript"; +```tsx import { CometChatMessageList } from "@cometchat/chat-uikit-react"; +import { CometChat } from "@cometchat/chat-sdk-javascript"; -export function MessageListDemo() { - const [chatUser, setChatUser] = React.useState(); - React.useEffect(() => { - CometChat.getUser("uid").then((user) => { - setChatUser(user); - }); - }, []); +function MessageListWithThreads() { + return ( + { + console.log("Thread:", message.getId()); + }} + /> + ); +} +``` - const getOnThreadRepliesClick = () => { - //your custom actions - }; +#### onReactionClick - return chatUser ? ( -
- -
- ) : null; +Fires when a reaction on a message bubble is clicked. + +```tsx +import { CometChatMessageList } from "@cometchat/chat-uikit-react"; +import { CometChat } from "@cometchat/chat-sdk-javascript"; + +function MessageListWithReactions() { + return ( + { + console.log("Reaction:", reaction, "on message:", message.getId()); + }} + /> + ); } ``` -
+#### onReactionListItemClick + +Fires when a specific reaction in the reaction detail view is clicked. - -```js -import React from "react"; +```tsx +import { CometChatMessageList } from "@cometchat/chat-uikit-react"; import { CometChat } from "@cometchat/chat-sdk-javascript"; + +function MessageListWithReactionDetail() { + return ( + { + console.log("Reaction detail:", reaction, message.getId()); + }} + /> + ); +} +``` + +#### onError + +Fires on internal errors. + +```tsx import { CometChatMessageList } from "@cometchat/chat-uikit-react"; +import { CometChat } from "@cometchat/chat-sdk-javascript"; -export function MessageListDemo() { - const [chatUser, setChatUser] = React.useState(null); +function MessageListWithError() { + return ( + { + console.error("MessageList error:", error); + }} + /> + ); +} +``` - React.useEffect(() => { - CometChat.getUser("uid").then((user) => { - setChatUser(user); - }); - }, []); +### Global UI Events - const getOnThreadRepliesClick = () => { - //your custom actions - }; +| Event | Fires when | Payload | +| --- | --- | --- | +| `CometChatMessageEvents.ccMessageEdited` | A message is edited | `IMessages` | +| `CometChatMessageEvents.ccMessageDeleted` | A message is deleted | `CometChat.BaseMessage` | +| `CometChatMessageEvents.ccMessageRead` | A message is read | `CometChat.BaseMessage` | +| `CometChatMessageEvents.ccReplyToMessage` | User replies to a message | `IMessages` | +| `CometChatUIEvents.ccOpenChat` | User opens a chat | `IOpenChat` | +| `CometChatUIEvents.ccActiveChatChanged` | Active chat changes | `IActiveChatChanged` | - return chatUser ? ( -
- -
- ) : null; +```tsx +import { useEffect } from "react"; +import { CometChatMessageEvents, CometChatUIEvents } from "@cometchat/chat-uikit-react"; + +function useMessageListEvents() { + useEffect(() => { + const editedSub = CometChatMessageEvents.ccMessageEdited.subscribe( + (data) => console.log("Edited:", data) + ); + const deletedSub = CometChatMessageEvents.ccMessageDeleted.subscribe( + (msg) => console.log("Deleted:", msg) + ); + + return () => { + editedSub?.unsubscribe(); + deletedSub?.unsubscribe(); + }; + }, []); } ``` -
+### SDK Events (Real-Time, Automatic) -
+The component listens to these SDK events internally: -##### 2. onError +| SDK Listener | Internal behavior | +| --- | --- | +| `onTextMessageReceived` / `onMediaMessageReceived` / `onCustomMessageReceived` | Appends new message to list | +| `onMessageEdited` / `onMessageDeleted` | Updates/removes message in list | +| `onTypingStarted` / `onTypingEnded` | Shows/hides typing indicator | +| `onMessagesDelivered` / `onMessagesRead` / `onMessagesDeliveredToAll` / `onMessagesReadByAll` | Updates receipt ticks | +| `onMessageModerated` | Updates moderated message state | -This action doesn't change the behavior of the component but rather listens for any errors that occur in the MessageList component. +--- - - -```ts -import React from "react"; -import { CometChat } from "@cometchat/chat-sdk-javascript"; -import { CometChatMessageList } from "@cometchat/chat-uikit-react"; +## Custom View Slots -export function MessageListDemo() { - const [chatUser, setChatUser] = React.useState(); - React.useEffect(() => { - CometChat.getUser("uid").then((user) => { - setChatUser(user); - }); - }, []); +| Slot | Type | Replaces | +| --- | --- | --- | +| `headerView` | `JSX.Element` | Area above the message list | +| `footerView` | `JSX.Element` | Area below the message list | +| `loadingView` | `JSX.Element` | Loading state | +| `emptyView` | `JSX.Element` | Empty state | +| `errorView` | `JSX.Element` | Error state | +| `templates` | `CometChatMessageTemplate[]` | Message bubble rendering | +| `textFormatters` | `CometChatTextFormatter[]` | Text formatting in messages | - function handleError(error: CometChat.CometChatException) { - throw new Error("your custom error action"); - } +### headerView - return chatUser ? ( -
- -
- ) : null; -} -``` +Custom view above the message list. -
+ + + - -```js -import React from "react"; + + +```tsx +import { useState, useEffect } from "react"; import { CometChat } from "@cometchat/chat-sdk-javascript"; -import { CometChatMessageList } from "@cometchat/chat-uikit-react"; +import { CometChatMessageList, CometChatButton } from "@cometchat/chat-uikit-react"; -export function MessageListDemo() { - const [chatUser, setChatUser] = React.useState(null); +function MessageListWithHeader() { + const [chatUser, setChatUser] = useState(); - React.useEffect(() => { - CometChat.getUser("uid").then((user) => { - setChatUser(user); - }); + useEffect(() => { + CometChat.getUser("uid").then((user) => setChatUser(user)); }, []); - const handleError = (error) => { - throw new Error("your custom error action"); - }; - return chatUser ? ( -
- -
+ + + + +
+ } + /> ) : null; } ``` -
+ +```css +.header-view { + display: flex; + width: 100%; + padding: 3px 16px; + align-items: flex-start; + gap: 5px; + background: #edeafa; +} +.header-view .cometchat .cometchat-button { + width: auto; + height: 32px; + border-radius: 1000px; + border: 1px solid #e8e8e8; + background: #fafafa; +} + +.header-view .cometchat .cometchat-button__text { + color: #6852d6; + font: 400 12px/14.4px Roboto; +} +``` +
-##### 3. onReactionClick +### footerView + +Custom view below the message list. -`onReactionClick` is triggered when you click on the reaction item of the message bubble. The `onReactionClick` action doesn't have a predefined behavior. You can override this action using the following code snippet. + + + -```ts -import React from "react"; -import { CometChat } from "@cometchat/chat-sdk-javascript"; -import { CometChatMessageList } from "@cometchat/chat-uikit-react"; +```tsx +import { CometChatMessageList, CometChatButton } from "@cometchat/chat-uikit-react"; -export function MessageListDemo() { - const [chatUser, setChatUser] = React.useState(); - React.useEffect(() => { - CometChat.getUser("uid").then((user) => { - setChatUser(user); - }); - }, []); +function MessageListWithFooter() { + return ( + + + +
+ } + /> + ); +} +``` +
+ +```css +.footer-view { + display: flex; + width: 100%; + padding: 3px 16px; + align-items: flex-start; + gap: 5px; + background: #edeafa; +} - function onReactionClick( - reaction: CometChat.ReactionCount, - message: CometChat.BaseMessage - ) { - //your custom action - } +.footer-view .cometchat .cometchat-button { + width: auto; + height: 32px; + border-radius: 1000px; + border: 1px solid #e8e8e8; + background: #fafafa; +} - return chatUser ? ( -
- -
- ) : null; +.footer-view .cometchat .cometchat-button__text { + color: #6852d6; + font: 400 12px/14.4px Roboto; } ``` -
+ - -```js -import React from "react"; +### templates + +Custom message bubble templates via [CometChatMessageTemplate](/ui-kit/react/message-template). + +```tsx +import { useState, useEffect } from "react"; import { CometChat } from "@cometchat/chat-sdk-javascript"; -import { CometChatMessageList } from "@cometchat/chat-uikit-react"; +import { + CometChatMessageList, + ChatConfigurator, + CometChatActionsIcon, +} from "@cometchat/chat-uikit-react"; -export function MessageListDemo() { - const [chatUser, setChatUser] = React.useState(null); +function MessageListCustomTemplates() { + const [chatUser, setChatUser] = useState(); - React.useEffect(() => { - CometChat.getUser("uid").then((user) => { - setChatUser(user); - }); + useEffect(() => { + CometChat.getUser("uid").then((user) => setChatUser(user)); }, []); - const onReactionClick = (reaction, message) => { - //your custom action + const getTemplates = () => { + const templates = ChatConfigurator.getDataSource().getAllMessageTemplates(); + templates.map((data) => { + data.options = (loggedInUser, message, group) => { + const defaults = ChatConfigurator.getDataSource().getMessageOptions( + loggedInUser, message, group + ); + defaults.push( + new CometChatActionsIcon({ + id: "custom", + title: "Custom Action", + onClick: () => console.log("custom action"), + }) + ); + return defaults; + }; + }); + return templates; }; return chatUser ? ( -
- -
+ ) : null; } ``` -
+### Date Time Formatting - +Customize timestamps using `CalendarObject`: -##### 4. onReactionListItemClick +```tsx +import { CometChatMessageList, CalendarObject } from "@cometchat/chat-uikit-react"; -`onReactionListItemClick` is triggered when you click on the reaction list item of the reaction list. The `onReactionListItemClick` action doesn't have a predefined behavior. You can override this action using the following code snippet. +function MessageListCustomDates() { + const dateFormat = new CalendarObject({ + today: "hh:mm A", + yesterday: "[yesterday]", + otherDays: "DD/MM/YYYY", + }); - - -```ts -import React from "react"; -import { CometChat } from "@cometchat/chat-sdk-javascript"; -import { CometChatMessageList } from "@cometchat/chat-uikit-react"; + return ( + + ); +} +``` -export function MessageListDemo() { - const [chatUser, setChatUser] = React.useState(); - React.useEffect(() => { - CometChat.getUser("uid").then((user) => { - setChatUser(user); - }); - }, []); +--- - function onReactionListItemClick( - reaction: CometChat.Reaction, - message: CometChat.BaseMessage - ) { - //your custom action - } +## Common Patterns - return chatUser ? ( -
- -
- ) : null; +### Threaded message list + +```tsx +import { CometChatMessageList } from "@cometchat/chat-uikit-react"; + +function ThreadedMessageList() { + return ( + + ); } ``` -
+### Hide all chrome — minimal list - -```js -import React from "react"; -import { CometChat } from "@cometchat/chat-sdk-javascript"; +```tsx import { CometChatMessageList } from "@cometchat/chat-uikit-react"; -export function MessageListDemo() { - const [chatUser, setChatUser] = React.useState(null); +function MinimalMessageList() { + return ( + + ); +} +``` - React.useEffect(() => { - CometChat.getUser("uid").then((user) => { - setChatUser(user); - }); - }, []); +### Left-aligned messages - const onReactionListItemClick = (reaction, message) => { - //your custom action - }; +```tsx +import { CometChatMessageList, MessageListAlignment } from "@cometchat/chat-uikit-react"; - return chatUser ? ( -
- -
- ) : null; +function LeftAlignedList() { + return ( + + ); } ``` -
+### AI conversation starters and smart replies -
- -### Filters +```tsx +import { CometChatMessageList } from "@cometchat/chat-uikit-react"; -##### 1. Messages Request Builder +function AIMessageList() { + return ( + + ); +} +``` -You can adjust the `MessagesRequestBuilder` in the MessageList Component to customize your message list. Numerous options are available to alter the builder to meet your specific needs. For additional details on `MessagesRequestBuilder`, please visit [MessagesRequestBuilder](/sdk/javascript/additional-message-filtering). +--- -In the example below, we are applying a filter to the messages based on a search substring and for a specific user. This means that only messages that contain the search term and are associated with the specified user will be displayed +## CSS Architecture - - -```ts -import React from "react"; -import { CometChat } from "@cometchat/chat-sdk-javascript"; -import { CometChatMessageList } from "@cometchat/chat-uikit-react"; +The component uses CSS custom properties (design tokens) defined in `@cometchat/chat-uikit-react/css-variables.css`. The cascade: -export function MessageListDemo() { - const [chatUser, setChatUser] = React.useState(); - React.useEffect(() => { - CometChat.getUser("uid").then((user) => { - setChatUser(user); - }); - }, []); +1. Global tokens set on the `.cometchat` root wrapper. +2. Component CSS (`.cometchat-message-list`) consumes these tokens via `var()`. +3. Overrides target `.cometchat-message-list` descendant selectors. - return chatUser ? ( -
- -
- ) : null; -} -``` +### Key Selectors -
+| Target | Selector | +| --- | --- | +| Root | `.cometchat-message-list` | +| Error state | `.cometchat-message-list__error-state-view` | +| Footer smart replies | `.cometchat-message-list__footer-smart-replies` | +| Footer conversation starters | `.cometchat-message-list__footer-conversation-starter` | +| Outgoing message bubble | `.cometchat-message-bubble-outgoing` | +| Incoming message bubble | `.cometchat-message-bubble-incoming` | +| Message bubble status info | `.cometchat-message-bubble__status-info-view` | +| Thread view replies | `.cometchat-message-bubble__thread-view-replies` | +| Text bubble | `.cometchat-message-bubble .cometchat-text-bubble` | +| Date separator | `.cometchat-message-bubble__status-info-view .cometchat-date` | - -```js -import React from "react"; -import { CometChat } from "@cometchat/chat-sdk-javascript"; -import { CometChatMessageList } from "@cometchat/chat-uikit-react"; +### Customization Matrix -export function MessageListDemo() { - const [chatUser, setChatUser] = React.useState(null); +| What to change | Where | Property/API | Example | +| --- | --- | --- | --- | +| Handle thread clicks | Component props | `onThreadRepliesClick` | `onThreadRepliesClick={(msg) => openThread(msg)}` | +| Filter messages | Component props | `messagesRequestBuilder` | `messagesRequestBuilder={builder}` | +| Toggle visibility | Component props | `hide` boolean props | `hideReceipts={true}` | +| Custom message bubbles | Component props | `templates` | `templates={customTemplates}` | +| Add header/footer | Component props | `headerView` / `footerView` | `headerView={
...
}` | +| Change colors, fonts, spacing | Global CSS | Target `.cometchat-message-list` class | `.cometchat-message-bubble-outgoing { background: blue; }` | - React.useEffect(() => { - CometChat.getUser("uid").then((user) => { - setChatUser(user); - }); - }, []); +--- - return chatUser ? ( -
- -
- ) : null; -} -``` +## Accessibility -
+Message bubbles are rendered as semantic elements. Date separators provide temporal context. The list supports keyboard scrolling. Thread reply counts are interactive and keyboard-focusable. Reaction buttons activate on Enter/Space. Avatar images include the sender name as alt text. -
+--- - +--- -The following parameters in messageRequestBuilder will always be altered inside the message list +## Props -1. UID -2. GUID +All props are optional. Sorted alphabetically. - +### customSoundForMessages -##### 2. Reactions Request Builder +URL to a custom audio file for incoming message notifications. -You can adjust the `ReactionsRequestBuilder` in the MessageList Component to customize and fetch the reactions for the messages. Numerous options are available to alter the builder to meet your specific needs. +| | | +| --- | --- | +| Type | `string` | +| Default | `undefined` | - - -```ts -import React from "react"; -import { CometChat } from "@cometchat/chat-sdk-javascript"; -import { CometChatMessageList } from "@cometchat/chat-uikit-react"; +--- -export function MessageListDemo() { - const [chatUser, setChatUser] = React.useState(); - React.useEffect(() => { - CometChat.getUser("uid").then((user) => { - setChatUser(user); - }); - }, []); +### disableSoundForMessages - return chatUser ? ( -
- -
- ) : null; -} -``` +Disables the notification sound for incoming messages. -
+| | | +| --- | --- | +| Type | `boolean` | +| Default | `true` | - -```js -import React from "react"; -import { CometChat } from "@cometchat/chat-sdk-javascript"; -import { CometChatMessageList } from "@cometchat/chat-uikit-react"; +--- -export function MessageListDemo() { - const [chatUser, setChatUser] = React.useState(null); +### emptyView - React.useEffect(() => { - CometChat.getUser("uid").then((user) => { - setChatUser(user); - }); - }, []); +Custom component displayed when there are no messages. - return chatUser ? ( -
- -
- ) : null; -} -``` +| | | +| --- | --- | +| Type | `JSX.Element` | +| Default | Built-in empty state | -
+--- -
+### errorView -### Events +Custom component displayed when an error occurs. -[Events](/ui-kit/react/components-overview#events) are emitted by a `Component`. By using event you can extend existing functionality. Being global events, they can be applied in Multiple Locations and are capable of being Added or Removed. +| | | +| --- | --- | +| Type | `JSX.Element` | +| Default | Built-in error state | -The list of events emitted by the Message List component is as follows. +--- -| Event | Description | -| ----------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------ | -| **ccOpenChat** | this event alerts the listeners if the logged-in user has opened a user or a group chat. | -| **ccMessageEdited** | Triggers whenever a loggedIn user edits any message from the list of messages .it will have three states such as: inProgress, success and error. | -| **ccReplyToMessage** | Triggers whenever a loggedIn user replies to any message from the list of messages .it will have three states such as: inProgress, success and error. | -| **ccMessageDeleted** | Triggers whenever a loggedIn user deletes any message from the list of messages. | -| **ccActiveChatChanged** | This event is triggered when the user navigates to a particular chat window. | -| **ccMessageRead** | Triggers whenever a loggedIn user reads any message. | +### footerView -Adding `CometChatMessageEvents` Listener's +Custom component displayed below the message list. - - -```ts -import { CometChatMessageEvents, CometChatUIEvents } from "@cometchat/chat-uikit-react"; +| | | +| --- | --- | +| Type | `JSX.Element` | +| Default | `undefined` | -const ccOpenChat = CometChatUIEvents.ccOpenChat.subscribe(() => { - // Your Code -}); +--- -const ccMessageEdited = CometChatMessageEvents.ccMessageEdited.subscribe(() => { - // Your Code -}); +### goToMessageId -const ccReplyToMessage = CometChatMessageEvents.ccReplyToMessage.subscribe(() => { - // Your Code -}); +Scrolls to the specified message on initial load. -const ccMessageDeleted = CometChatMessageEvents.ccMessageDeleted.subscribe(() => { - // Your Code -}); +| | | +| --- | --- | +| Type | `string` | +| Default | `undefined` | -const ccActiveChatChanged = CometChatUIEvents.ccActiveChatChanged.subscribe(() => { - // Your Code -}); +--- -const ccMessageRead = CometChatMessageEvents.ccMessageRead.subscribe(() => { - // Your Code -}); -``` +### group - +The group for group conversation messages. - -```js -import { CometChatMessageEvents, CometChatUIEvents } from "@cometchat/chat-uikit-react"; +| | | +| --- | --- | +| Type | `CometChat.Group` | +| Default | `undefined` | -const ccOpenChat = CometChatUIEvents.ccOpenChat.subscribe(() => { - // Your Code -}); +--- -const ccMessageEdited = CometChatMessageEvents.ccMessageEdited.subscribe(() => { - // Your Code -}); +### headerView -const ccReplyToMessage = CometChatMessageEvents.ccReplyToMessage.subscribe(() => { - // Your Code -}); +Custom component displayed above the message list. -const ccMessageDeleted = CometChatMessageEvents.ccMessageDeleted.subscribe(() => { - // Your Code -}); +| | | +| --- | --- | +| Type | `JSX.Element` | +| Default | `undefined` | -const ccActiveChatChanged = CometChatUIEvents.ccActiveChatChanged.subscribe(() => { - // Your Code -}); +--- -const ccMessageRead = CometChatMessageEvents.ccMessageRead.subscribe(() => { - // Your Code -}); -``` +### hideAvatar - +Hides avatars on messages. - +| | | +| --- | --- | +| Type | `boolean` | +| Default | `false` | -*** +--- -Removing `CometChatMessageEvents` Listener's +### hideCopyMessageOption - - -```ts -ccMessageEdited?.unsubscribe(); -ccReplyToMessage?.unsubscribe(); -ccActiveChatChanged?.unsubscribe(); -``` +Hides the copy message option. - +| | | +| --- | --- | +| Type | `boolean` | +| Default | `false` | - -```js -ccMessageEdited?.unsubscribe(); -ccReplyToMessage?.unsubscribe(); -ccActiveChatChanged?.unsubscribe(); -``` +--- - +### hideDateSeparator - +Hides date separators between message groups. -*** +| | | +| --- | --- | +| Type | `boolean` | +| Default | `false` | -## Customization +--- -To fit your app's design requirements, you can customize the appearance of the Message List component. We provide exposed properties that allow you to modify the experience and behavior according to your specific needs. +### hideDeleteMessageOption -### Style +Hides the delete message option. -You can set the css to the MessageList Component Component to customize the styling. +| | | +| --- | --- | +| Type | `boolean` | +| Default | `false` | -**Example** +--- - - - +### hideEditMessageOption - - -```ts -import React from "react"; -import { CometChat } from "@cometchat/chat-sdk-javascript"; -import { CometChatMessageList } from "@cometchat/chat-uikit-react"; +Hides the edit message option. -; -``` +| | | +| --- | --- | +| Type | `boolean` | +| Default | `false` | - +--- - -```css -.cometchat-message-bubble__body - .cometchat-text-bubble.cometchat-text-bubble-incoming - .cometchat-text-bubble__body-text { - font-family: "SF Pro"; -} -``` +### hideError - +Hides the default and custom error views. - +| | | +| --- | --- | +| Type | `boolean` | +| Default | `false` | -### Functionality +--- -These are a set of small functional customizations that allow you to fine-tune the overall experience of the component. With these, you can change text, set custom icons, and toggle the visibility of UI elements. +### hideFlagMessageOption - - -```ts -import React from "react"; -import { CometChat } from "@cometchat/chat-sdk-javascript"; -import { CometChatMessageList } from "@cometchat/chat-uikit-react"; +Hides the "Report Message" option. -export function MessageListDemo() { - const [chatUser, setChatUser] = React.useState(); - React.useEffect(() => { - CometChat.getUser("uid").then((user) => { - setChatUser(user); - }); - }, []); +| | | +| --- | --- | +| Type | `boolean` | +| Default | `false` | - return chatUser ? ( -
- -
- ) : null; -} -``` +--- -
+### hideFlagRemarkField - -```js -import React from "react"; -import { CometChat } from "@cometchat/chat-sdk-javascript"; -import { CometChatMessageList } from "@cometchat/chat-uikit-react"; +Hides the remark text area in the flag message dialog. -export function MessageListDemo() { - const [chatUser, setChatUser] = React.useState(null); +| | | +| --- | --- | +| Type | `boolean` | +| Default | `false` | - React.useEffect(() => { - CometChat.getUser("uid").then((user) => { - setChatUser(user); - }); - }, []); +--- - return chatUser ? ( -
- -
- ) : null; -} -``` +### hideGroupActionMessages -
+Hides group action messages (join, leave, kick, etc.). -
+| | | +| --- | --- | +| Type | `boolean` | +| Default | `false` | -*** - -Below is a list of customizations along with corresponding code snippets - -| Property | Description | Code | -| ------------------------------------ | ------------------------------------------------------------------------------------------- | ---------------------------------------------- | -| **Hide Date Separator** | Hides the visibility of the date separator in the message list. | `hideDateSeparator={true}` | -| **Hide Sticky Date** | Hides the sticky date header in the message list. | `hideStickyDate={true}` | -| **Hide Receipts** | Hides the visibility of receipts in the message list. | `hideReceipts={true}` | -| **Hide Error** | Hides the default & custom error view passed in the `errorView` prop. | `hideError={true}` | -| **Hide Reply In Thread Option** | Hides the option to reply to messages in a thread. | `hideReplyInThreadOption={true}` | -| **Hide Translate Message Option** | Hides the option to translate messages. | `hideTranslateMessageOption={true}` | -| **Hide Edit Message Option** | Hides the option to edit messages. | `hideEditMessageOption={true}` | -| **Hide Delete Message Option** | Hides the option to delete messages. | `hideDeleteMessageOption={true}` | -| **Hide Reaction Option** | Hides the option to react to messages. | `hideReactionOption={true}` | -| **Hide Message Privately Option** | Hides the option to message a user privately. | `hideMessagePrivatelyOption={true}` | -| **Hide Copy Message Option** | Hides the option to copy messages. | `hideCopyMessageOption={true}` | -| **Hide Message Info Option** | Hides the option to view message information. | `hideMessageInfoOption={true}` | -| **Hide Reply Option** | Hides the reply option for a message. | `hideReplyOption={true}` | -| **Hide Avatar** | Hides avatars for messages. | `hideAvatar={true}` | -| **Hide Group Action Messages** | Hides group action messages. | `hideGroupActionMessages={true}` | -| **Hide Conversation Starters** | Hides the visibility of the conversation starters in the message list. | `hideConversationStarters={true}` | -| **Hide Smart Replies** | Hides the visibility of the smart replies in the message list. | `hideSmartReplies={true}` | -| **Hide Moderation View** | Hides the moderation view shown below the message bubble in the bottom view when a message is moderated. | `hideModerationView={true}` | -| **Hide Flag Message Option** | Hides the "Report Message" option from message actions menu. | `hideFlagMessageOption={true}` | -| **Hide Flag Remark Field** | Hides the remark text area in the flag message dialog. | `hideFlagRemarkField={true}` | -| **Parent Message ID** | Unique identifier of the parent message for displaying threaded conversations. | `parentMessageId={1234}` | -| **User** | A `CometChat.User` object representing the participant of the chat. | `user={chatUser}` | -| **Group** | A `CometChat.Group` object representing the group whose chat messages are displayed. | `group={chatGroup}` | -| **Message Alignment** | Specifies the alignment of messages in the list (e.g., left, right). | `messageAlignment={MessageListAlignment.left}` | -| **Scroll To Bottom On New Messages** | Automatically scrolls the message list to the bottom when a new message arrives. | `scrollToBottomOnNewMessages={true}` | -| **Quick Options Count** | Specifies how many message options are visible in the main menu by default. | `quickOptionsCount={3}` | -| **Disable Sound For Messages** | Disables the sound effect when new messages arrive. | `disableSoundForMessages={true}` | -| **Custom Sound For Messages** | Specifies a custom sound file to play when new messages arrive. | `customSoundForMessages="sound.mp3"` | -| **Smart Replies Keywords** | Sets the keywords on which the smart replies should be triggered in the message list. | `smartRepliesKeywords={['why', 'how']}` | -| **Smart Replies Delay Duration** | Sets the delay duration (in milliseconds) before smart replies are shown. | `smartRepliesDelayDuration={5000}` | -| **Start From Unread Messages** | When set to true, the chat will load from the first unread message if unread messages exist, otherwise loads from the latest messages. Default is false. | `startFromUnreadMessages={true}` | -| **Show Mark Unread Option** | When set to true, shows the "Mark Unread" option in the message actions menu. This option will only appear for received messages, not for the user's own messages. Default is false. | `showMarkAsUnreadOption={true}` | -| **Empty View** | Custom empty state view to display when there are no messages. | `emptyView={}` | -| **Error View** | A custom view displayed when there are no messages. | `errorView={}` | -| **Loading View** | A custom view displayed while messages are being fetched. | `loadingView={}` | -| **Go To MessageId** | The ID of the message that the list should automatically scroll to when it is first loaded. | `goToMessageId={1}` | - -*** - -### Advanced - -For advanced-level customization, you can set custom views to the component. This lets you tailor each aspect of the component to fit your exact needs and application aesthetics. You can create and define your views, layouts, and UI elements and then incorporate those into the component. - -#### Templates - -[CometChatMessageTemplate](/ui-kit/react/message-template) is a pre-defined structure for creating message views that can be used as a starting point or blueprint for creating message views often known as message bubbles. For more information, you can refer to [CometChatMessageTemplate](/ui-kit/react/message-template). - -You can set message Templates to MessageList by using the following code snippet. +--- - - -```ts -import React from "react"; -import { CometChat } from "@cometchat/chat-sdk-javascript"; -import { - CometChatMessageList, - ChatConfigurator, - CometChatActionsIcon, -} from "@cometchat/chat-uikit-react"; +### hideMessageInfoOption -export function MessageListDemo() { - const [chatUser, setChatUser] = React.useState(); - React.useEffect(() => { - CometChat.getUser("uid").then((user) => { - setChatUser(user); - }); - }, []); +Hides the message info option. - const getCustomOptions = ( - loggedInUser: CometChat.User, - message: CometChat.BaseMessage, - group?: CometChat.Group - ) => { - const defaultOptions: any = - ChatConfigurator.getDataSource().getMessageOptions( - loggedInUser, - message, - group - ); - const myView: any = new CometChatActionsIcon({ - id: "custom id", - title: "your custom title for options", - iconURL: "your custom icon url for options", - onClick: () => console.log("custom action"), - }); - defaultOptions.push(myView); - return defaultOptions; - }; +| | | +| --- | --- | +| Type | `boolean` | +| Default | `false` | - const getTemplates = () => { - let templates = ChatConfigurator.getDataSource().getAllMessageTemplates(); - templates.map((data) => { - data.options = ( - loggedInUser: CometChat.User, - message: CometChat.BaseMessage, - group?: CometChat.Group - ) => getCustomOptions(loggedInUser, message, group); - }); - return templates; - }; +--- - return chatUser ? ( -
- -
- ) : null; -} -``` +### hideMessagePrivatelyOption -
+Hides the "Message Privately" option. - -```js -import React from "react"; -import { CometChat } from "@cometchat/chat-sdk-javascript"; -import { - CometChatMessageList, - ChatConfigurator, - CometChatActionsIcon, -} from "@cometchat/chat-uikit-react"; +| | | +| --- | --- | +| Type | `boolean` | +| Default | `false` | -export function MessageListDemo() { - const [chatUser, setChatUser] = React.useState(null); +--- - React.useEffect(() => { - CometChat.getUser("uid").then((user) => { - setChatUser(user); - }); - }, []); +### hideModerationView - const getCustomOptions = (loggedInUser, message, theme, group) => { - const defaultOptions = ChatConfigurator.getDataSource().getMessageOptions( - loggedInUser, - message, - group - ); - const myView = new CometChatActionsIcon({ - id: "custom id", - title: "your custom title for options", - iconURL: "your custom icon url for options", - onClick: () => console.log("custom action"), - }); - defaultOptions.push(myView); - return defaultOptions; - }; +Hides the moderation view below moderated messages. - const getTemplates = () => { - let templates = ChatConfigurator.getDataSource().getAllMessageTemplates(); - templates.map((data) => { - data.options = (loggedInUser, message, group) => - getCustomOptions(loggedInUser, message, group); - }); - return templates; - }; +| | | +| --- | --- | +| Type | `boolean` | +| Default | `false` | - return chatUser ? ( -
- -
- ) : null; -} -``` +--- -
+### hideReactionOption -
+Hides the reaction option. -*** +| | | +| --- | --- | +| Type | `boolean` | +| Default | `false` | -#### Separator DateTime Format +--- -The `separatorDateTimeFormat` property allows you to customize the **Date Separator** timestamp displayed in the Message List. +### hideReceipts -Default Date Time Format: +Hides read/delivery receipt indicators. -```javascript -new CalendarObject({ - today: "today" // Example: "today" - yesterday: "yesterday", // Example: "yesterday" - otherDays: `DD MMM, YYYY`, // Example: "25 Jan, 2025" -}); -``` +| | | +| --- | --- | +| Type | `boolean` | +| Default | `false` | -The following example demonstrates how to modify the **Date Separator** timestamp format using a custom [`CalendarObject`](/ui-kit/react/localize#calendarobject). +--- - - -```ts -import { - CometChatMessageList, - CalendarObject, -} from "@cometchat/chat-uikit-react"; +### hideReplyInThreadOption -// Define a custom date format pattern -function getDateFormat() { - const dateFormat = new CalendarObject({ - today: `hh:mm A`, // Example: "10:30 AM" - yesterday: `[yesterday]`, // Example: "yesterday" - otherDays: `DD/MM/YYYY`, // Example: "25/05/2025" - }); - return dateFormat; -} +Hides the "Reply in Thread" option. -// Apply the custom format to the CometChatMessageList component -; -``` +| | | +| --- | --- | +| Type | `boolean` | +| Default | `false` | - +--- - +### hideReplyOption - +Hides the reply option. -**Fallback Mechanism** +| | | +| --- | --- | +| Type | `boolean` | +| Default | `false` | -* If you **do not** pass any property in the [**CalendarObject**](/ui-kit/react/localize#calendarobject), the component will first check the [**global configuration**](/ui-kit/react/localize#customisation). If the property is **also missing in the global configuration**, it will **fallback to the component's default formatting**. +--- - +### hideStickyDate -*** +Hides the sticky date header. -#### Sticky DateTime Format +| | | +| --- | --- | +| Type | `boolean` | +| Default | `false` | -The `stickyDateTimeFormat` property allows you to customize the **Sticky Date** timestamp displayed in the Message List. +--- -!\[]\(Screenshot HERE) +### hideTranslateMessageOption -Default Date Time Format: +Hides the translate message option. -```javascript -new CalendarObject({ - today: "today" // Example: "today" - yesterday: "yesterday", // Example: "yesterday" - otherDays: `DD MMM, YYYY`, // Example: "25 Jan, 2025" -}); -``` +| | | +| --- | --- | +| Type | `boolean` | +| Default | `false` | -The following example demonstrates how to modify the **Sticky Date** timestamp format using a custom [`CalendarObject`](/ui-kit/react/localize#calendarobject). +--- - - -```ts -import { - CometChatMessageList, - CalendarObject, -} from "@cometchat/chat-uikit-react"; +### isAgentChat -// Define a custom date format pattern -function getDateFormat() { - const dateFormat = new CalendarObject({ - today: `hh:mm A`, // Example: "10:30 AM" - yesterday: `[yesterday]`, // Example: "yesterday" - otherDays: `DD/MM/YYYY`, // Example: "25/05/2025" - }); - return dateFormat; -} +Toggles AI Agent functionality for the message list. -// Apply the custom format to the CometChatMessageList component -; -``` +| | | +| --- | --- | +| Type | `boolean` | +| Default | `false` | - +--- - +### loadingView - +Custom component displayed during the loading state. -**Fallback Mechanism** +| | | +| --- | --- | +| Type | `JSX.Element` | +| Default | Built-in shimmer | -* If you **do not** pass any property in the [**CalendarObject**](/ui-kit/react/localize#calendarobject), the component will first check the [**global configuration**](/ui-kit/react/localize#customisation). If the property is **also missing in the global configuration**, it will **fallback to the component's default formatting**. +--- - +### loadLastAgentConversation -*** +Loads the most recent existing agent conversation on mount. -#### Message SentAt DateTime Format +| | | +| --- | --- | +| Type | `boolean` | +| Default | `false` | -The `messageSentAtDateTimeFormat` property allows you to customize the **Message SentAt** timestamp displayed in the Message List. +--- -Default Date Time Format: +### messageAlignment -```javascript -new CalendarObject({ - today: "hh:mm A" // Example: "12:00 PM" - yesterday: "hh:mm A", // Example: "01:00 AM" - otherDays: `hh:mm A`, // Example: "09:30 PM" -}); -``` +Controls message alignment. -The following example demonstrates how to modify the **Message SentAt** timestamp format using a custom [`CalendarObject`](/ui-kit/react/localize#calendarobject). +| | | +| --- | --- | +| Type | `MessageListAlignment` | +| Default | `MessageListAlignment.standard` | - - ```ts -import { - CometChatMessageList, - CalendarObject, -} from "@cometchat/chat-uikit-react"; - -// Define a custom date format pattern -function getDateFormat() { - const dateFormat = new CalendarObject({ - today: `hh:mm A`, // Example: "10:30 AM" - yesterday: `[yesterday]`, // Example: "yesterday" - otherDays: `DD/MM/YYYY`, // Example: "25/05/2025" - }); - return dateFormat; +enum MessageListAlignment { + left, // 0 + standard, // 1 } - -// Apply the custom format to the CometChatMessageList component -; ``` - +--- - +### messageInfoDateTimeFormat - +Format for message info timestamps. -**Fallback Mechanism** +| | | +| --- | --- | +| Type | `CalendarObject` | +| Default | Component default | -* If you **do not** pass any property in the [**CalendarObject**](/ui-kit/react/localize#calendarobject), the component will first check the [**global configuration**](/ui-kit/react/localize#customisation). If the property is **also missing in the global configuration**, it will **fallback to the component's default formatting**. +--- - +### messageSentAtDateTimeFormat -*** +Format for message sent-at timestamps. -#### Message Info DateTime Format +| | | +| --- | --- | +| Type | `CalendarObject` | +| Default | Component default | -The `messageInfoDateTimeFormat` property allows you to customize the **Message Info** timestamp displayed in the Message List. +--- -Default Date Time Format: +### messagesRequestBuilder -```ruby -new CalendarObject({ - today: `DD MMM, hh:mm A`, // Example: "29 Jan, 04:34 AM" - yesterday: `DD MMM, hh:mm A`, // Example: "29 Jan, 04:34 AM" - otherDays: `DD MMM, hh:mm A`, // Example: "29 Jan, 04:34 AM" -}); -``` +Controls which messages load and in what order. -The following example demonstrates how to modify the **Message Info** timestamp format using a custom [`CalendarObject`](/ui-kit/react/localize#calendarobject). +| | | +| --- | --- | +| Type | `CometChat.MessagesRequestBuilder` | +| Default | SDK default | - - -```ts -import { - CometChatMessageList, - CalendarObject, -} from "@cometchat/chat-uikit-react"; +UID/GUID are always overridden internally. -// Define a custom date format pattern -function getDateFormat() { - const dateFormat = new CalendarObject({ - today: `hh:mm A`, // Example: "10:30 AM" - yesterday: `[yesterday]`, // Example: "yesterday" - otherDays: `DD/MM/YYYY`, // Example: "25/05/2025" - }); - return dateFormat; -} +--- -// Apply the custom format to the CometChatMessageList component -; -``` +### onError - +Callback fired when the component encounters an error. - +| | | +| --- | --- | +| Type | `((error: CometChat.CometChatException) => void) \| null` | +| Default | `undefined` | - +--- -**Fallback Mechanism** +### onReactionClick -* If you **do not** pass any property in the [**CalendarObject**](/ui-kit/react/localize#calendarobject), the component will first check the [**global configuration**](/ui-kit/react/localize#customisation). If the property is **also missing in the global configuration**, it will **fallback to the component's default formatting**. +Callback fired when a reaction on a message is clicked. - +| | | +| --- | --- | +| Type | `(reaction: CometChat.ReactionCount, message: CometChat.BaseMessage) => void` | +| Default | `undefined` | -*** +--- -#### Headerview +### onReactionListItemClick -You can set custom headerView to the Message List component using the following method. +Callback fired when a reaction list item is clicked. -The customized chat interface is displayed below. +| | | +| --- | --- | +| Type | `(reaction: CometChat.Reaction, message: CometChat.BaseMessage) => void` | +| Default | `undefined` | - - - +--- -Use the following code to achieve the customization shown above. +### onThreadRepliesClick - - -```ts -import React from "react"; -import { CometChat } from "@cometchat/chat-sdk-javascript"; -import { CometChatMessageList } from "@cometchat/chat-uikit-react"; -import notesIcon from "../../assets/notesIcon.svg"; -import pinnedIcon from "../../assets/pinnedIcon.svg"; -import savedIcon from "../../assets/savedIcon.svg"; +Callback fired when a threaded message reply count is clicked. -export function MessageListDemo() { - const [chatUser, setChatUser] = React.useState(); +| | | +| --- | --- | +| Type | `(message: CometChat.BaseMessage) => void` | +| Default | `undefined` | - React.useEffect(() => { - CometChat.getUser("uid").then((user) => { - setChatUser(user); - }); - }, []); +--- - const getHeaderView = () => { - return ( -
- - - -
- ); - }; +### parentMessageId - return chatUser ? ( -
- -
- ) : null; -} -``` +Displays threaded conversation for the specified parent message. -
+| | | +| --- | --- | +| Type | `number` | +| Default | `undefined` | - -```js -import React from "react"; -import { CometChat } from "@cometchat/chat-sdk-javascript"; -import { CometChatMessageList } from "@cometchat/chat-uikit-react"; -import notesIcon from "../../assets/notesIcon.svg"; -import pinnedIcon from "../../assets/pinnedIcon.svg"; -import savedIcon from "../../assets/savedIcon.svg"; +--- -export function MessageListDemo() { - const [chatUser, setChatUser] = React.useState(null); +### quickOptionsCount - React.useEffect(() => { - CometChat.getUser("uid").then((user) => { - setChatUser(user); - }); - }, []); +Number of message options visible in the main menu before overflow. - const getHeaderView = () => { - return ( -
- - - -
- ); - }; +| | | +| --- | --- | +| Type | `number` | +| Default | `3` | - return chatUser ? ( -
- -
- ) : null; -} -``` +--- -
+### reactionsRequestBuilder - -```css -.header-view { - display: flex; - width: 100%; - padding: 3px 16px; - align-items: flex-start; - gap: 5px; - background: #edeafa; -} +Controls how reactions are fetched for messages. -.header-view .cometchat .cometchat-button { - width: auto; - height: 32px; - border-radius: 1000px; - border: 1px solid #e8e8e8; - background: #fafafa; - color: #6852d6; - text-align: center; -} +| | | +| --- | --- | +| Type | `CometChat.ReactionsRequestBuilder` | +| Default | `undefined` | -.header-view .cometchat .cometchat-button__text { - color: #6852d6; - text-align: center; - font: 400 12px/14.4px Roboto; - font-style: normal; -} +--- -.header-view .cometchat .cometchat-button__icon { - background-color: #6852d6; - display: flex; - justify-content: center; - align-items: center; -} -``` +### scrollToBottomOnNewMessages - +Auto-scrolls to bottom when new messages arrive. -
+| | | +| --- | --- | +| Type | `boolean` | +| Default | `false` | -*** +--- -#### FooterView +### separatorDateTimeFormat -You can set custom footerview to the Message List component using the following method. +Format for date separator timestamps. -The customized chat interface is displayed below. +| | | +| --- | --- | +| Type | `CalendarObject` | +| Default | Component default | - - - +--- -Use the following code to achieve the customization shown above. +### showConversationStarters - - -```ts -import React from "react"; -import { CometChat } from "@cometchat/chat-sdk-javascript"; -import { CometChatMessageList } from "@cometchat/chat-uikit-react"; -import iceBreakersIcon from "../../assets/iceBreakersIcon.svg"; -import callIcon from "../../assets/callIcon.svg"; -import instagramIcon from "../../assets/instagramIcon.svg"; -import snapchatIcon from "../../assets/snapchatIcon.svg"; +Shows AI conversation starters. -export function MessageListDemo() { - const [chatUser, setChatUser] = React.useState(); +| | | +| --- | --- | +| Type | `boolean` | +| Default | `false` | - React.useEffect(() => { - CometChat.getUser("uid").then((user) => { - setChatUser(user); - }); - }, []); +--- - const getFooterView = () => { - return ( -
- - - - -
- ); - }; +### showMarkAsUnreadOption - return chatUser ? ( -
- -
- ) : null; -} -``` +Shows "Mark Unread" option in message actions. -
+| | | +| --- | --- | +| Type | `boolean` | +| Default | `false` | - -```js -import React from "react"; -import { CometChat } from "@cometchat/chat-sdk-javascript"; -import { CometChatMessageList } from "@cometchat/chat-uikit-react"; -import iceBreakersIcon from "../../assets/iceBreakersIcon.svg"; -import callIcon from "../../assets/callIcon.svg"; -import instagramIcon from "../../assets/instagramIcon.svg"; -import snapchatIcon from "../../assets/snapchatIcon.svg"; +--- -export function MessageListDemo() { - const [chatUser, setChatUser] = React.useState(null); +### showScrollbar - React.useEffect(() => { - CometChat.getUser("uid").then((user) => { - setChatUser(user); - }); - }, []); +Shows the scrollbar in the message list. - const getFooterView = () => { - return ( -
- - - - -
- ); - }; +| | | +| --- | --- | +| Type | `boolean` | +| Default | `false` | - return chatUser ? ( -
- -
- ) : null; -} -``` +--- -
+### showSmartReplies - -```css -.footer-view { - display: flex; - width: 100%; - padding: 3px 16px; - align-items: flex-start; - gap: 5px; - background: #edeafa; -} +Shows AI smart replies. -.footer-view .cometchat .cometchat-button { - width: auto; - height: 32px; - border-radius: 1000px; - border: 1px solid #e8e8e8; - background: #fafafa; - color: #6852d6; - text-align: center; -} +| | | +| --- | --- | +| Type | `boolean` | +| Default | `false` | -.footer-view .cometchat .cometchat-button__text { - color: #6852d6; - text-align: center; - font: 400 12px/14.4px Roboto; - font-style: normal; -} +--- -.footer-view .cometchat .cometchat-button__icon { - background-color: #6852d6; - display: flex; - justify-content: center; - align-items: center; -} -``` +### smartRepliesDelayDuration - +Delay in milliseconds before smart replies appear. -
+| | | +| --- | --- | +| Type | `number` | +| Default | `10000` | -*** +--- -#### TextFormatters +### smartRepliesKeywords -Assigns the list of text formatters. If the provided list is not null, it sets the list. Otherwise, it assigns the default text formatters retrieved from the data source. To configure the existing Mentions look and feel check out [CometChatMentionsFormatter](/ui-kit/react/mentions-formatter-guide) +Keywords that trigger smart replies. - - -```ts -import { CometChatTextFormatter } from "@cometchat/chat-uikit-react"; -import DialogHelper from "./Dialog"; -import { CometChat } from "@cometchat/chat-sdk-javascript"; +| | | +| --- | --- | +| Type | `string[]` | +| Default | `["what", "when", "why", "who", "where", "how", "?"]` | -class ShortcutFormatter extends CometChatTextFormatter { - private shortcuts: { [key: string]: string } = {}; - private dialogIsOpen: boolean = false; - private dialogHelper = new DialogHelper(); - private currentShortcut: string | null = null; // Track the currently open shortcut - - constructor() { - super(); - this.setTrackingCharacter("!"); - CometChat.callExtension("message-shortcuts", "GET", "v1/fetch", undefined) - .then((data: any) => { - if (data && data.shortcuts) { - this.shortcuts = data.shortcuts; - } - }) - .catch((error) => console.log("error fetching shortcuts", error)); - } +--- - onKeyDown(event: KeyboardEvent) { - const caretPosition = - this.currentCaretPosition instanceof Selection - ? this.currentCaretPosition.anchorOffset - : 0; - const textBeforeCaret = this.getTextBeforeCaret(caretPosition); - - const match = textBeforeCaret.match(/!([a-zA-Z]+)$/); - if (match) { - const shortcut = match[0]; - const replacement = this.shortcuts[shortcut]; - if (replacement) { - // Close the currently open dialog, if any - if (this.dialogIsOpen && this.currentShortcut !== shortcut) { - this.closeDialog(); - } - this.openDialog(replacement, shortcut); - } - } - } +### startFromUnreadMessages - getCaretPosition() { - if (!this.currentCaretPosition?.rangeCount) return { x: 0, y: 0 }; - const range = this.currentCaretPosition?.getRangeAt(0); - const rect = range.getBoundingClientRect(); - return { - x: rect.left, - y: rect.top, - }; - } +Loads from the first unread message if available. - openDialog(buttonText: string, shortcut: string) { - this.dialogHelper.createDialog( - () => this.handleButtonClick(buttonText), - buttonText - ); - this.dialogIsOpen = true; - this.currentShortcut = shortcut; - } +| | | +| --- | --- | +| Type | `boolean` | +| Default | `false` | - closeDialog() { - this.dialogHelper.closeDialog(); // Use DialogHelper to close the dialog - this.dialogIsOpen = false; - this.currentShortcut = null; - } +--- - handleButtonClick = (buttonText: string) => { - if (this.currentCaretPosition && this.currentRange) { - // Inserting the replacement text corresponding to the shortcut - const shortcut = Object.keys(this.shortcuts).find( - (key) => this.shortcuts[key] === buttonText - ); - if (shortcut) { - const replacement = this.shortcuts[shortcut]; - this.addAtCaretPosition( - replacement, - this.currentCaretPosition, - this.currentRange - ); - } - } - if (this.dialogIsOpen) { - this.closeDialog(); - } - }; +### stickyDateTimeFormat - getFormattedText(text: string): string { - return text; - } +Format for sticky date header timestamps. - private getTextBeforeCaret(caretPosition: number): string { - if ( - this.currentRange && - this.currentRange.startContainer && - typeof this.currentRange.startContainer.textContent === "string" - ) { - const textContent = this.currentRange.startContainer.textContent; - if (textContent.length >= caretPosition) { - return textContent.substring(0, caretPosition); - } - } - return ""; - } -} +| | | +| --- | --- | +| Type | `CalendarObject` | +| Default | Component default | -export default ShortcutFormatter; -``` +--- - +### templates - -```tsx -import React from "react"; -import ReactDOM from "react-dom"; +Custom message bubble templates. -interface DialogProps { - onClick: () => void; - buttonText: string; -} +| | | +| --- | --- | +| Type | `CometChatMessageTemplate[]` | +| Default | SDK defaults | -const Dialog: React.FC = ({ onClick, buttonText }) => { - console.log("buttonText", buttonText); +See [CometChatMessageTemplate](/ui-kit/react/message-template). - return ( -
- -
- ); -}; +--- -export default class DialogHelper { - private dialogContainer: HTMLDivElement | null = null; +### textFormatters - createDialog(onClick: () => void, buttonText: string) { - this.dialogContainer = document.createElement("div"); - document.body.appendChild(this.dialogContainer); +Custom text formatters for message content. - ReactDOM.render( - , - this.dialogContainer - ); - } +| | | +| --- | --- | +| Type | `CometChatTextFormatter[]` | +| Default | Default formatters from data source | - closeDialog() { - if (this.dialogContainer) { - ReactDOM.unmountComponentAtNode(this.dialogContainer); - this.dialogContainer.remove(); - this.dialogContainer = null; - } - } -} -``` +See [CometChatMentionsFormatter](/ui-kit/react/mentions-formatter-guide). -
+--- - -```tsx -import React from "react"; -import { CometChat } from "@cometchat/chat-sdk-javascript"; -import { CometChatMessageList } from "@cometchat/chat-uikit-react"; -import ShortcutFormatter from "./ShortCutFormatter"; +### user -export function MessageListDemo() { - const [chatUser, setChatUser] = React.useState(); - React.useEffect(() => { - CometChat.getUser("uid").then((user) => { - setChatUser(user); - }); - }, []); +The user for 1-on-1 conversation messages. - return chatUser ? ( -
- -
- ) : null; -} -``` +| | | +| --- | --- | +| Type | `CometChat.User` | +| Default | `undefined` | -
+--- -
+## Events + +| Event | Payload | Fires when | +| --- | --- | --- | +| `CometChatMessageEvents.ccMessageEdited` | `IMessages` | Message edited | +| `CometChatMessageEvents.ccMessageDeleted` | `CometChat.BaseMessage` | Message deleted | +| `CometChatMessageEvents.ccMessageRead` | `CometChat.BaseMessage` | Message read | +| `CometChatMessageEvents.ccReplyToMessage` | `IMessages` | User replies to message | +| `CometChatUIEvents.ccOpenChat` | `IOpenChat` | Chat opened | +| `CometChatUIEvents.ccActiveChatChanged` | `IActiveChatChanged` | Active chat changes | + +--- -*** +## CSS Selectors + +| Target | Selector | +| --- | --- | +| Root | `.cometchat-message-list` | +| Error state | `.cometchat-message-list__error-state-view` | +| Footer smart replies | `.cometchat-message-list__footer-smart-replies` | +| Footer conversation starters | `.cometchat-message-list__footer-conversation-starter` | +| Outgoing bubble | `.cometchat-message-bubble-outgoing` | +| Incoming bubble | `.cometchat-message-bubble-incoming` | +| Status info view | `.cometchat-message-bubble__status-info-view` | +| Thread view replies | `.cometchat-message-bubble__thread-view-replies` | +| Text bubble | `.cometchat-message-bubble .cometchat-text-bubble` | +| Delete bubble | `.cometchat-message-bubble .cometchat-delete-bubble` | diff --git a/ui-kit/react/message-template.mdx b/ui-kit/react/message-template.mdx index 7659b7286..e2946c811 100644 --- a/ui-kit/react/message-template.mdx +++ b/ui-kit/react/message-template.mdx @@ -1,282 +1,166 @@ --- title: "Message Template" +description: "Data structure defining how message bubbles render in CometChatMessageList — controls header, content, footer, bottom, status info, reply, and bubble views per message type and category." --- + +```json +{ + "component": "CometChatMessageTemplate", + "kind": "model-class", + "package": "@cometchat/chat-uikit-react", + "import": "import { CometChatMessageTemplate } from \"@cometchat/chat-uikit-react\";", + "description": "Data structure defining how message bubbles render in CometChatMessageList. Each template maps a type+category pair to view functions.", + "usage": "Pass an array of CometChatMessageTemplate instances to CometChatMessageList via the templates prop.", + "properties": { + "type": { "type": "string", "required": true, "description": "CometChat message type" }, + "category": { "type": "string", "default": "\"\"", "description": "CometChat message category" }, + "headerView": { "type": "function | null", "default": "null", "description": "Custom header view function" }, + "contentView": { "type": "function | null", "default": "null", "description": "Custom content view function" }, + "footerView": { "type": "function | null", "default": "null", "description": "Custom footer view function" }, + "bottomView": { "type": "function | null", "default": "null", "description": "Custom bottom view function" }, + "bubbleView": { "type": "function | null", "default": "null", "description": "Replaces entire bubble" }, + "statusInfoView": { "type": "function | null", "default": "null", "description": "Custom status info view function" }, + "replyView": { "type": "function | null", "default": "null", "description": "Custom reply preview function" }, + "options": { "type": "function", "description": "Returns action sheet items for long-press" } + }, + "relatedComponents": ["CometChatMessageList"], + "cssRootClass": null, + "events": null +} +``` + -## Overview - -MessageTemplate provides you with the capability to define and customize both the structure and the behavior of the Message Bubble. It acts as a schema or design blueprint for the creation of a variety of Message Bubble components, allowing you to manage the appearance and interactions of Message Bubble within your application effectively and consistently. - -### Structure - - - - - -The Message Bubble structure can typically be broken down into the following views: - -1. **Leading view**: This is where the sender's avatar is displayed. It's typically on the left of the Message Bubble for messages from others and on the right for messages from the current user. - -2. **Header view**: This displays the sender's name and is especially useful in group chats where multiple users are sending messages. - -3. **Reply view**: This view can be used to extend the Message Bubble with additional elements. It's typically placed above the Content view. - -4. **Content view**: This is the core of the Message Bubble where the message content (text, images, videos, etc.) is displayed. - -5. **Bottom view**: This view can be used to extend the Message Bubble with additional elements, such as link previews or a 'load more' button for long messages. It's typically placed beneath the Content view. - -6. **Thread view**: This is where the thread reply icon and reply counts are displayed. It's located below the footer view. - -7. **Footer view**: This is where the reactions are displayed. It's located at the bottom of the Message Bubble. - -8. **Status Info view**: This is where the timestamp of the message and its delivery or read status are displayed. It's located inside the Message Bubble just below the content view. - -*** - -### Properties - -MessageTemplate provides you with methods that allow you to alter various properties of the Message Bubble. These properties include aspects such as the `type` and `category` of a message, the appearance and behavior of the header, content, and footer sections of the message bubble, - -1. **type** - - Using `type` you can set the type of CometChatMessage, This will map your MessageTemplate to the corresponding CometChatMessage. You can set the MessageTemplates Type using the following code snippet. - -2. **category** - - Using `category` you can set the category of a MessageTemplate. This will create a MessageTemplate with the specified category and link it with a CometChatMessage of the same category. - - Please refer to our guide on [Message Categories](/sdk/javascript/message-structure-and-hierarchy) for a deeper understanding of message categories. - -3. **headerView** - - The `headerView` method allows you to assign a custom header view to the Message Bubble. By default, it is configured to display the sender's name. - -4. **contentView** - - The `contentView` method allows you to assign a custom content view to the Message Bubble. By default, it displays the Text Bubble, Image Bubble, File Bubble, Audio Bubble, or Video Bubble depending on the message type. - -5. **footerView** - - The `footerView` method allows you to assign a custom Footer view to the Message Bubble. By default it shows thr reactions for the message bubble. - -6. **bottomView** - - The `bottomView` method allows you to assign a custom Bottom view to the Message Bubble. By defuault is has buttons such as link previews or a 'load more' button for long messages. - -7. **bubbleView** +## What It Is - The `bubbleView` method allows you to assign a custom Bubble view to the Message Bubble. By default, headerView, contentView, statusInfoView and footerView together form a message bubble. +`CometChatMessageTemplate` is a model class, not a rendered component. Each instance maps a message `type` + `category` pair to a set of view functions that control how that message renders inside `CometChatMessageList`. Pass an array of templates to the `templates` prop on `CometChatMessageList`. -8. **statusInfoView** +```tsx +import { useState, useEffect } from "react"; +import { + CometChatMessageList, + CometChatMessageTemplate, + CometChatUIKit, + CometChatUIKitConstants, +} from "@cometchat/chat-uikit-react"; +import { CometChat } from "@cometchat/chat-sdk-javascript"; - The `statusInfoView` method allows you to assign a custom status info view to the Message Bubble. By default, it displays the receipt and timestamp. +function CustomTemplateDemo() { + const [chatGroup, setChatGroup] = useState(); + const [templates, setTemplates] = useState([]); -9. **replyView** + useEffect(() => { + CometChat.getGroup("guid").then((group) => setChatGroup(group)); - The `replyView` method allows you to assign a custom reply view to the Message Bubble. By default, it displays the preview of the replied message. + const allTemplates = CometChatUIKit.getDataSource().getAllMessageTemplates(); + const modified = allTemplates.map((t) => { + if ( + t.type === CometChatUIKitConstants.MessageTypes.text && + t.category === CometChatUIKitConstants.MessageCategory.message + ) { + t.headerView = (message: CometChat.BaseMessage) => ( + <>{message.getSender().getName()} • 🗓️ In meeting + ); + } + return t; + }); + setTemplates(modified); + }, []); -10. **options** + if (!chatGroup) return null; - The `options` lets you set the list of actions that a user can perform on a message. This includes actions like reacting to, editing, or deleting a message. + return ; +} +``` -*** +--- -## Customization +## Template Structure -Let's dive into how you can use the [properties](#properties) of MessageTemplate to customize an existing template or add a new one to the [MessageList](/ui-kit/react/message-list) component. +A message bubble is composed of these view slots, each overridable per template: -The first step is to fetch the list of existing templates when you want to modify or add to them. This can be done using the getAllMessageTemplates() method from the DataSource of the CometChatUIKit class. +| View | Default rendering | Signature | +| --- | --- | --- | +| `headerView` | Sender name | `(message: CometChat.BaseMessage, alignment: MessageBubbleAlignment, textFormatters?: CometChatTextFormatter[]) => JSX.Element \| null` | +| `contentView` | Text / image / video / audio / file bubble | `(message: CometChat.BaseMessage, alignment: MessageBubbleAlignment, textFormatters?: CometChatTextFormatter[]) => JSX.Element \| null` | +| `footerView` | Reactions | `(message: CometChat.BaseMessage, alignment: MessageBubbleAlignment) => JSX.Element \| null` | +| `bottomView` | Link previews, "load more" | `(message: CometChat.BaseMessage, alignment: MessageBubbleAlignment) => JSX.Element \| null` | +| `statusInfoView` | Receipt + timestamp | `(message: CometChat.BaseMessage, alignment: MessageBubbleAlignment, hideReceipts?: boolean, messageSentAtDateTimeFormat?: CalendarObject, showError?: boolean) => JSX.Element \| null` | +| `replyView` | Reply preview | `(message: CometChat.BaseMessage, alignment?: MessageBubbleAlignment, onReplyViewClicked?: (msg: CometChat.BaseMessage) => void, textFormatters?: CometChatTextFormatter[]) => JSX.Element \| null` | +| `bubbleView` | Entire bubble (overrides all above) | `(message: CometChat.BaseMessage, alignment: MessageBubbleAlignment) => JSX.Element \| null` | +| `options` | Long-press action sheet | `(loggedInUser: CometChat.User, message: CometChat.BaseMessage, group?: CometChat.Group) => CometChatMessageOption[]` | -```javascript -let definedTemplates = CometChatUIKit.getDataSource().getAllMessageTemplates(); -``` +--- -### Existing Templates +## Fetching Existing Templates -You will need to first get the MessageTemplate object for the type of message you want to customize. You will be customizing the text message bubble here. The code snippet to get the Text MessageTemplate is as follows. +Retrieve the built-in templates and modify specific ones: - - -```ts +```tsx import { CometChatUIKit, CometChatUIKitConstants, + CometChatMessageTemplate, } from "@cometchat/chat-uikit-react"; -let allTemplates: CometChatMessageTemplate[] = +const allTemplates: CometChatMessageTemplate[] = CometChatUIKit.getDataSource().getAllMessageTemplates(); -for (let i = 0; i < allTemplates.length; i++) { - if (allTemplates[i].type === CometChatUIKitConstants.MessageTypes.text) { - //customize allTemplates[i] - } -} -``` - - - - -```js -import { - CometChatUIKit, - CometChatUIKitConstants, -} from "@cometchat/chat-uikit-react"; -let allTemplates = CometChatUIKit.getDataSource().getAllMessageTemplates(); for (let i = 0; i < allTemplates.length; i++) { if (allTemplates[i].type === CometChatUIKitConstants.MessageTypes.text) { - //customize allTemplates[i] + // customize allTemplates[i] } } ``` - - - - -You will be using [Message List](/ui-kit/react/message-list) component using the `templates` prop of `CometChatMessageList` component. - - - -```ts -import { CometChatMessageList } from "@cometchat/uikit-react"; - -; -``` - - - - -```js -import { CometChatMessageList } from "@cometchat/uikit-react"; - -; -``` - - - - +--- -#### HeaderView +## Common Patterns -The `headerView` method of MessageTemplate allows you to add custom views to the header of your message bubbles. In the example below, we will add a custom header view of every text message in the MessageList. +### Custom header with status badge - - -```ts -import React, { useEffect, useState } from "react"; -import { - CometChatMessageList, - CometChatUIKit, - CometChatUIKitConstants, -} from "@cometchat/chat-uikit-react"; -import { CometChat } from "@cometchat/chat-sdk-javascript"; - -const CustomMessageTemplate = () => { - const [templates, setTemplates] = React.useState( - [] - ); - const [chatGroup, setChatGroup] = React.useState(); - - useEffect(() => { - CometChat.getGroup("guid").then((group) => { - setChatGroup(group); - }); - - let definedTemplates: CometChatMessageTemplate[] = - CometChatUIKit.getDataSource().getAllMessageTemplates(); - const template = definedTemplates.map((templates) => { - if ( - templates.type === CometChatUIKitConstants.MessageTypes.text && - templates.category === CometChatUIKitConstants.MessageCategory.message - ) { - templates.headerView = (message: CometChat.BaseMessage) => - getHeaderView(message); - return templates; - } - return templates; - }); - setTemplates(template); - }, []); - - const getHeaderView = (message: CometChat.BaseMessage) => { - return <> {message.getSender().getName()} • 🗓️ In meeting; - }; - - return ( -
- {chatGroup && ( - - )} -
- ); -}; - -export { CustomMessageTemplate }; -``` - -
- - -```js -import React, { useEffect, useState } from "react"; +```tsx +import { useState, useEffect } from "react"; import { CometChatMessageList, CometChatUIKit, CometChatUIKitConstants, + CometChatMessageTemplate, } from "@cometchat/chat-uikit-react"; import { CometChat } from "@cometchat/chat-sdk-javascript"; -const CustomMessageTemplate = () => { - const [templates, setTemplates] = useState([]); - const [chatGroup, setChatGroup] = useState(null); +function HeaderViewDemo() { + const [chatGroup, setChatGroup] = useState(); + const [templates, setTemplates] = useState([]); useEffect(() => { - CometChat.getGroup("guid").then((group) => { - setChatGroup(group); - }); + CometChat.getGroup("guid").then((group) => setChatGroup(group)); - let definedTemplates = - CometChatUIKit.getDataSource().getAllMessageTemplates(); - const template = definedTemplates.map((templates) => { + const definedTemplates = CometChatUIKit.getDataSource().getAllMessageTemplates(); + const modified = definedTemplates.map((t) => { if ( - templates.type === CometChatUIKitConstants.MessageTypes.text && - templates.category === CometChatUIKitConstants.MessageCategory.message + t.type === CometChatUIKitConstants.MessageTypes.text && + t.category === CometChatUIKitConstants.MessageCategory.message ) { - templates.headerView = (message: CometChat.BaseMessage) => - getHeaderView(message); - return templates; + t.headerView = (message: CometChat.BaseMessage) => ( + <>{message.getSender().getName()} • 🗓️ In meeting + ); } - return templates; + return t; }); - setTemplates(template); + setTemplates(modified); }, []); - const getHeaderView = (message: CometChat.BaseMessage) => { - return <> {message.getSender().getName()} • 🗓️ In meeting; - }; - - return ( -
- {chatGroup && ( - - )} -
- ); -}; + if (!chatGroup) return null; -export { CustomMessageTemplate }; + return ; +} ``` -
- -
- -#### Contentview - -The `contentview` method of MessageTemplate allows you to add a custom view to the content of your message bubbles. In the example below, we will add a custom layout to the content view of every text message in the MessageList. +### Custom content view for a custom message type @@ -284,8 +168,8 @@ The `contentview` method of MessageTemplate allows you to add a custom view to t -```ts -import React from "react"; +```tsx +import { useState, useEffect } from "react"; import { CometChatMessageList, CometChatUIKit, @@ -293,164 +177,43 @@ import { CometChatMessageTemplate, } from "@cometchat/chat-uikit-react"; import { CometChat } from "@cometchat/chat-sdk-javascript"; -import bannerImage from "../../assets/banner.svg"; -const CustomMessageTemplate = () => { - const [templates, setTemplates] = React.useState( - [] - ); - const [chatGroup, setChatGroup] = React.useState(); +function ContentViewDemo() { + const [chatGroup, setChatGroup] = useState(); + const [templates, setTemplates] = useState([]); - React.useEffect(() => { - CometChat.getGroup("guid").then((group) => { - setChatGroup(group); - }); + useEffect(() => { + CometChat.getGroup("guid").then((group) => setChatGroup(group)); - let definedTemplates: CometChatMessageTemplate[] = - CometChatUIKit.getDataSource().getAllMessageTemplates(); + const definedTemplates = CometChatUIKit.getDataSource().getAllMessageTemplates(); const CUSTOM_MESSAGE_TYPE = "customType"; - let customMessageTemplate = new CometChatMessageTemplate({ + const customTemplate = new CometChatMessageTemplate({ type: CUSTOM_MESSAGE_TYPE, category: CometChatUIKitConstants.MessageCategory.custom, - contentView: (message: CometChat.BaseMessage) => getContentView(message), - }); - definedTemplates.push(customMessageTemplate); - setTemplates(definedTemplates); - }, []); - - const getContentView = (message: CometChat.BaseMessage) => { - return ( -
-
- -
-
-
+ contentView: (message: CometChat.BaseMessage) => ( +
+
Blazer Casual
Men's Tailored Regular Fit Blazer
-
-
- $37.99{" "} - $74.00 -
-
- Free Delivery + $37.99 $74.00
+
Buy now
-
Buy now
-
- ); - }; - - const getMessageRequestBuilder = () => { - const CUSTOM_MESSAGE_TYPE = "customType"; - let categories = CometChatUIKit.getDataSource().getAllMessageCategories(); - categories.push(CometChatUIKitConstants.MessageCategory.custom); - let types = CometChatUIKit.getDataSource().getAllMessageTypes(); - types.push(CUSTOM_MESSAGE_TYPE); - return new CometChat.MessagesRequestBuilder() - .setCategories(categories) - .setTypes(types) - .hideReplies(true) - .setLimit(30); - }; - - return ( -
- {chatGroup && ( - - )} -
- ); -}; - -export { CustomMessageTemplate }; -``` - - - - -```js -import React from "react"; -import { - CometChatMessageList, - CometChatUIKit, - CometChatUIKitConstants, - CometChatMessageTemplate, -} from "@cometchat/chat-uikit-react"; -import { CometChat } from "@cometchat/chat-sdk-javascript"; -import bannerImage from "../../assets/banner.svg"; - -const CustomMessageTemplate = () => { - const [templates, setTemplates] = React.useState([]); - const [chatGroup, setChatGroup] = React.useState(); - - React.useEffect(() => { - CometChat.getGroup("guid").then((group) => { - setChatGroup(group); + ), }); - - let definedTemplates = - CometChatUIKit.getDataSource().getAllMessageTemplates(); - const CUSTOM_MESSAGE_TYPE = "customType"; - let customMessageTemplate = new CometChatMessageTemplate({ - type: CUSTOM_MESSAGE_TYPE, - category: CometChatUIKitConstants.MessageCategory.custom, - contentView: (message: CometChat.BaseMessage) => getContentView(message), - }); - definedTemplates.push(customMessageTemplate); + definedTemplates.push(customTemplate); setTemplates(definedTemplates); }, []); - const getContentView = (message: CometChat.BaseMessage) => { - return ( -
-
- -
-
-
-
Blazer Casual
-
- Men's Tailored Regular Fit Blazer -
-
-
-
- $37.99{" "} - $74.00 -
-
- Free Delivery -
-
-
-
Buy now
-
- ); - }; - const getMessageRequestBuilder = () => { const CUSTOM_MESSAGE_TYPE = "customType"; - let categories = CometChatUIKit.getDataSource().getAllMessageCategories(); + const categories = CometChatUIKit.getDataSource().getAllMessageCategories(); categories.push(CometChatUIKitConstants.MessageCategory.custom); - let types = CometChatUIKit.getDataSource().getAllMessageTypes(); + const types = CometChatUIKit.getDataSource().getAllMessageTypes(); types.push(CUSTOM_MESSAGE_TYPE); return new CometChat.MessagesRequestBuilder() .setCategories(categories) @@ -459,30 +222,20 @@ const CustomMessageTemplate = () => { .setLimit(30); }; + if (!chatGroup) return null; + return ( -
- {chatGroup && ( - - )} -
+ ); -}; - -export { CustomMessageTemplate }; +} ``` -
- - + ```css -.content-view__header-banner { - border-radius: 12px; -} - .content-view__body { height: 105px; display: flex; @@ -490,7 +243,6 @@ export { CustomMessageTemplate }; flex-direction: column; text-align: left; gap: 16px; - align-self: stretch; } .content-view__body-title { @@ -514,32 +266,21 @@ export { CustomMessageTemplate }; text-decoration: line-through; } -.content-view__body-delivery-type { - color: #727272; - font: 400 14px/1.2 Roboto; -} - .content-footer { display: flex; height: 40px; padding: 8px 20px; justify-content: center; align-items: center; - gap: 8px; - align-self: stretch; border-top: 1px solid #dcdcdc; color: #6852d6; font: 500 14px/1.2 Roboto; } ``` - - -#### BottomView - -The `bottomView` method of MessageTemplate allows you to add a custom button view to your message bubbles. In the example below, we will add a custom bottom view to every text message in the MessageList. +### Custom bottom view with warning @@ -547,115 +288,47 @@ The `bottomView` method of MessageTemplate allows you to add a custom button vie -```ts -import React, { useEffect, useState } from "react"; +```tsx +import { useState, useEffect } from "react"; import { CometChatMessageList, CometChatUIKit, CometChatUIKitConstants, + CometChatMessageTemplate, } from "@cometchat/chat-uikit-react"; import { CometChat } from "@cometchat/chat-sdk-javascript"; -const CustomMessageTemplate = () => { - const [templates, setTemplates] = React.useState( - [] - ); - const [chatGroup, setChatGroup] = React.useState(); +function BottomViewDemo() { + const [chatGroup, setChatGroup] = useState(); + const [templates, setTemplates] = useState([]); useEffect(() => { - CometChat.getGroup("guid").then((group) => { - setChatGroup(group); - }); + CometChat.getGroup("guid").then((group) => setChatGroup(group)); - let definedTemplates: CometChatMessageTemplate[] = - CometChatUIKit.getDataSource().getAllMessageTemplates(); - const template = definedTemplates.map((templates) => { + const definedTemplates = CometChatUIKit.getDataSource().getAllMessageTemplates(); + const modified = definedTemplates.map((t) => { if ( - templates.type === CometChatUIKitConstants.MessageTypes.text && - templates.category === CometChatUIKitConstants.MessageCategory.message + t.type === CometChatUIKitConstants.MessageTypes.text && + t.category === CometChatUIKitConstants.MessageCategory.message ) { - templates.bottomView = (message: CometChat.BaseMessage) => - getBottomView(message); - return templates; + t.bottomView = (message: CometChat.BaseMessage) => ( +
+ According to guidelines you cannot share contact +
+ ); } - return templates; + return t; }); - setTemplates(template); + setTemplates(modified); }, []); - const getBottomView = (message: CometChat.BaseMessage) => { - return ( -
- According to guidelines you cannot - share contact -
- ); - }; - - return ( -
- {chatGroup && ( - - )} -
- ); -}; - -export { CustomMessageTemplate }; -``` - -
- - -```js -import React, { useEffect, useState } from "react"; -import { CometChatMessageList, CometChatUIKit, CometChatUIKitConstants } from '@cometchat/chat-uikit-react'; -import { CometChat } from "@cometchat/chat-sdk-javascript"; - -const CustomMessageTemplate = () => { - const [templates, setTemplates] = React.useState([]); - const [chatGroup, setChatGroup] = React.useState(); - - useEffect(() => { - CometChat.getGroup("guid").then((group) => { - setChatGroup(group); - }) - - let definedTemplates = CometChatUIKit.getDataSource().getAllMessageTemplates(); - const template = definedTemplates.map((templates) => { - if (templates.type === CometChatUIKitConstants.MessageTypes.text && - templates.category === CometChatUIKitConstants.MessageCategory.message) { - templates.bottomView = (message: CometChat.BaseMessage) => getBottomView(message) - return templates; - } - return templates - }) - setTemplates(template); - }, []); - - const getBottomView = (message: CometChat.BaseMessage) => { - return ( -
- According to guidelines you cannot share contact -
) - } - - return ( -
- {chatGroup && } -
- ); -}; + if (!chatGroup) return null; -export { CustomMessageTemplate }; + return ; +} ``` -
- - + ```css .cometchat .cometchat-message-bubble__body { border-radius: 12px 12px 0px 0px; @@ -673,421 +346,91 @@ export { CustomMessageTemplate }; 0deg, rgba(244, 70, 73, 0.2) 0%, rgba(244, 70, 73, 0.2) 100% - ), #fff; + ), + #fff; padding: 0px 8px 0px 5px; } - -.error-icon { - display: flex; - width: 12px; - height: 12px; - justify-content: center; - align-items: center; - flex-shrink: 0; - flex-shrink: 0; - -webkit-mask: url("../assets/infoIcon.svg") center center no-repeat; - mask: url("../assets/infoIcon.svg") center center no-repeat; - -webkit-mask-size: contain; - mask-size: contain; - background-color: #f44649; -} ``` - -
-#### FooterView - -The `footerView` method of MessageTemplate allows you to add a footer view to your message bubbles. In the example below, we will add a custom footer view to every text message in the MessageList. +### Replace entire bubble - + -```ts -import React, { useEffect, useState } from "react"; +```tsx +import { useState, useEffect } from "react"; import { CometChatMessageList, CometChatUIKit, CometChatUIKitConstants, + CometChatMessageTemplate, + MessageBubbleAlignment, + CometChatUIKitLoginListener, + MessageReceiptUtils, + Receipts, + isMessageSentByMe, } from "@cometchat/chat-uikit-react"; import { CometChat } from "@cometchat/chat-sdk-javascript"; -const CustomMessageTemplate = () => { - const [templates, setTemplates] = React.useState( - [] - ); - const [chatGroup, setChatGroup] = React.useState(); +function BubbleViewDemo() { + const [chatGroup, setChatGroup] = useState(); + const [templates, setTemplates] = useState([]); useEffect(() => { - CometChat.getGroup("guid").then((group) => { - setChatGroup(group); - }); + CometChat.getGroup("guid").then((group) => setChatGroup(group)); - let definedTemplates: CometChatMessageTemplate[] = - CometChatUIKit.getDataSource().getAllMessageTemplates(); - const template = definedTemplates.map((templates) => { + const definedTemplates = CometChatUIKit.getDataSource().getAllMessageTemplates(); + const modified = definedTemplates.map((t) => { if ( - templates.type === CometChatUIKitConstants.MessageTypes.text && - templates.category === CometChatUIKitConstants.MessageCategory.message + t.type === CometChatUIKitConstants.MessageTypes.text && + t.category === CometChatUIKitConstants.MessageCategory.message ) { - templates.footerView = (message: CometChat.BaseMessage) => - getFooterView(message); - return templates; + t.bubbleView = ( + message: CometChat.BaseMessage, + alignment: MessageBubbleAlignment + ) => { + const isSentByMe = isMessageSentByMe( + message, + CometChatUIKitLoginListener.getLoggedInUser()! + ); + let textMessage = ""; + if (message instanceof CometChat.TextMessage) { + textMessage = message.getText(); + } + return ( +
+
+
{textMessage}
+
+
+ ); + }; } - return templates; + return t; }); - setTemplates(template); + setTemplates(modified); }, []); - const getFooterView = (message: CometChat.BaseMessage) => { - if (message.getReactions().length > 0) { - return ( - <> - - - ); - } else { - return null; - } - }; - - return ( -
- {chatGroup && ( - - )} -
- ); -}; + if (!chatGroup) return null; -export { CustomMessageTemplate }; + return ; +} ``` -
- - -```js -import React, { useEffect, useState } from "react"; -import { - CometChatMessageList, - CometChatUIKit, - CometChatUIKitConstants, -} from "@cometchat/chat-uikit-react"; -import { CometChat } from "@cometchat/chat-sdk-javascript"; - -const CustomMessageTemplate = () => { - const [templates, setTemplates] = React.useState([]); - const [chatGroup, setChatGroup] = React.useState(); - - useEffect(() => { - CometChat.getGroup("guid").then((group) => { - setChatGroup(group); - }); - - let definedTemplates = - CometChatUIKit.getDataSource().getAllMessageTemplates(); - const template = definedTemplates.map((templates) => { - if ( - templates.type === CometChatUIKitConstants.MessageTypes.text && - templates.category === CometChatUIKitConstants.MessageCategory.message - ) { - templates.footerView = (message: CometChat.BaseMessage) => - getFooterView(message); - return templates; - } - return templates; - }); - setTemplates(template); - }, []); - - const getFooterView = (message: CometChat.BaseMessage) => { - if (message.getReactions().length > 0) { - return ( - <> - - - ); - } else { - return null; - } - }; - - return ( -
- {chatGroup && ( - - )} -
- ); -}; - -export { CustomMessageTemplate }; -``` - -
- - -```css -.cometchat .cometchat-message-bubble__body-footer-view { - display: flex; - align-items: center; - border-top: 1px solid #dcdcdc; - border-radius: 0px 0px 12px 12px; - background: #e8e8e8; - padding: 8px; -} - -.cometchat-message-bubble__body-wrapper:has( - .cometchat-message-bubble__body-footer-view - ) - .cometchat-message-bubble__body { - border-radius: 12px 12px 0px 0px; -} -``` - - - -
- -#### BubbleView - -The `bubbleView` method of MessageTemplate allows you to add a bubble view to your message bubbles. In the example below, we will add a custom bubble view to the text message in the MessageList. - - - - - - - -```ts -import React, { useEffect, useState } from "react"; -import { - CometChatMessageList, - CometChatUIKit, - CometChatUIKitConstants, - CometChatMessageTemplate, - Receipts, - MessageBubbleAlignment, - CometChatUIKitLoginListener, - MessageReceiptUtils, - isMessageSentByMe, -} from "@cometchat/chat-uikit-react"; -import { CometChat } from "@cometchat/chat-sdk-javascript"; -import readIcon from "../../assets/message-read.svg"; -import sentIcon from "../../assets/message-sent.svg"; -import deliveredIcon from "../../assets/message-delivered.svg"; - -const CustomMessageTemplate = () => { - const [templates, setTemplates] = React.useState( - [] - ); - const [chatGroup, setChatGroup] = React.useState(); - - useEffect(() => { - CometChat.getGroup("guid").then((group) => { - setChatGroup(group); - }); - - let definedTemplates = - CometChatUIKit.getDataSource().getAllMessageTemplates(); - const template = definedTemplates.map((templates) => { - if ( - templates.type === CometChatUIKitConstants.MessageTypes.text && - templates.category === CometChatUIKitConstants.MessageCategory.message - ) { - templates.bubbleView = ( - message: CometChat.BaseMessage, - alignment: MessageBubbleAlignment - ) => getBubbleView(message, alignment); - return templates; - } - return templates; - }); - setTemplates(template); - }, []); - - const formatTime = (timestamp: number): string => { - const date = new Date(timestamp * 1000); // Convert to milliseconds - const hours = date.getHours(); - const minutes = date.getMinutes(); - const period = hours >= 12 ? "PM" : "AM"; - const formattedHours = hours % 12 || 12; - const formattedMinutes = minutes < 10 ? "0" + minutes : minutes; - return `${formattedHours}:${formattedMinutes} ${period}`; - }; - - const getBubbleView = ( - message: CometChat.BaseMessage, - alignment: MessageBubbleAlignment - ) => { - const isSentByMe = isMessageSentByMe( - message, - CometChatUIKitLoginListener.getLoggedInUser()! - ); - - let textMessage = ""; - if (message instanceof CometChat.TextMessage) { - textMessage = message.getText(); - } - - const receipt = MessageReceiptUtils.getReceiptStatus(message); - let status = sentIcon; - - if (receipt === Receipts.delivered) { - status = deliveredIcon; - } else if (receipt === Receipts.read) { - status = readIcon; - } else { - status = sentIcon; - } - - return ( -
-
-
{textMessage}
-
-
-
- {formatTime(message.getSentAt())} - {isSentByMe && } -
-
- ); - }; - - return ( -
- {chatGroup && ( - - )} -
- ); -}; - -export { CustomMessageTemplate }; -``` - -
- - -```js -import React, { useEffect, useState } from "react"; -import { CometChatMessageList, CometChatUIKit, CometChatUIKitConstants,CometChatMessageTemplate,Receipts,MessageBubbleAlignment,CometChatUIKitLoginListener,MessageReceiptUtils, isMessageSentByMe } from '@cometchat/chat-uikit-react'; -import { CometChat } from "@cometchat/chat-sdk-javascript"; -import readIcon from "../../assets/message-read.svg"; -import sentIcon from "../../assets/message-sent.svg"; -import deliveredIcon from "../../assets/message-delivered.svg"; - -const CustomMessageTemplate = () => { - const [templates, setTemplates] = React.useState([]); - const [chatGroup, setChatGroup] = React.useState(); - - useEffect(() => { - CometChat.getGroup("guid").then((group) => { - setChatGroup(group); - }) - - let definedTemplates = CometChatUIKit.getDataSource().getAllMessageTemplates(); - const template = definedTemplates.map((templates) => { - if (templates.type === CometChatUIKitConstants.MessageTypes.text && - templates.category === CometChatUIKitConstants.MessageCategory.message) { - templates.bubbleView = (message, alignment) => getBubbleView(message, alignment) - return templates; - } - return templates - }) - setTemplates(template); - }, []); - - const formatTime = (timestamp) => { - const date = new Date(timestamp * 1000); // Convert to milliseconds - const hours = date.getHours(); - const minutes = date.getMinutes(); - const period = hours >= 12 ? 'PM' : 'AM'; - const formattedHours = hours % 12 || 12; - const formattedMinutes = minutes < 10 ? '0' + minutes : minutes; - return `${formattedHours}:${formattedMinutes} ${period}`; - }; - - const getBubbleView = (message,alignment) => { - const isSentByMe = isMessageSentByMe( - message, - CometChatUIKitLoginListener.getLoggedInUser()! - ); - - let textMessage = ""; - if (message instanceof CometChat.TextMessage) { - textMessage = message.getText(); - } - - const receipt = MessageReceiptUtils.getReceiptStatus(message); - let status = sentIcon; - - if (receipt === Receipts.delivered) { - status = deliveredIcon; - } else if (receipt === Receipts.read) { - status = readIcon; - } else { - status = sentIcon; - } - - return ( -
-
-
{textMessage}
-
-
-
- {formatTime(message.getSentAt())} - {isSentByMe && ( - - )} -
-
- ); - }; - - return ( -
- {chatGroup && } -
- ); -}; - -export { CustomMessageTemplate }; -``` - -
- - -```css -.bubble-view { - display: flex; - flex-direction: column; - width: 100%; - padding: 20px; - gap: 12px; -} + +```css +.bubble-view { + display: flex; + flex-direction: column; + width: 100%; + padding: 20px; + gap: 12px; +} .bubble-view__outgoing { align-items: flex-end; @@ -1102,15 +445,11 @@ export { CustomMessageTemplate }; display: flex; flex-direction: column; align-items: flex-end; - position: relative; } .bubble-view__content__text { width: fit-content; - display: flex; padding: 4px; - flex-direction: column; - align-items: flex-end; border-radius: 2px 2px 0px 2px; background: #6852d6; color: white; @@ -1120,816 +459,267 @@ export { CustomMessageTemplate }; background-color: #e8e8e8; color: #141414; } - -.bubble-view__content__time { - width: fit-content; - display: flex; - border-radius: 2px 2px 0px 2px; - color: #727272; - gap: 4px; - color: #727272; - text-align: right; - font: 400 10/14 Roboto; - font-style: normal; -} - -.bubble-view__outgoing .triangle { - position: absolute; - bottom: -10px; - right: 0px; - width: 0; - height: 9px; - border-left: 18px solid transparent; - border-top: 10px solid #5a4fcf; -} - -.bubble-view__incoming .triangle { - position: absolute; - bottom: -10px; - left: 0px; - width: 0; - height: 9px; - border-right: 18px solid transparent; - border-top: 10px solid #e8e8e8; -} ``` - -
-#### StatusInfoView - -The `statusInfoView` method of MessageTemplate allows you to add a status info view to your message bubbles. In the example below, we will add a custom status info view to every text message in the MessageList. +### Custom action sheet options - + - - -```ts -import React, { useEffect, useState } from "react"; +```tsx +import { useState, useEffect } from "react"; import { CometChatMessageList, CometChatUIKit, CometChatUIKitConstants, + CometChatMessageTemplate, + CometChatActionsIcon, } from "@cometchat/chat-uikit-react"; import { CometChat } from "@cometchat/chat-sdk-javascript"; -const CustomMessageTemplate = () => { - const [templates, setTemplates] = React.useState( - [] - ); - const [chatGroup, setChatGroup] = React.useState(); +function OptionsDemo() { + const [chatGroup, setChatGroup] = useState(); + const [templates, setTemplates] = useState([]); useEffect(() => { - CometChat.getGroup("guid").then((group) => { - setChatGroup(group); - }); + CometChat.getGroup("guid").then((group) => setChatGroup(group)); - let definedTemplates: CometChatMessageTemplate[] = - CometChatUIKit.getDataSource().getAllMessageTemplates(); - const template = definedTemplates.map((templates) => { + const definedTemplates = CometChatUIKit.getDataSource().getAllMessageTemplates(); + const modified = definedTemplates.map((t) => { if ( - templates.type === CometChatUIKitConstants.MessageTypes.text && - templates.category === CometChatUIKitConstants.MessageCategory.message + t.type === CometChatUIKitConstants.MessageTypes.text && + t.category === CometChatUIKitConstants.MessageCategory.message ) { - templates.statusInfoView = (message: CometChat.BaseMessage) => - getStatusInfo(message); - return templates; + t.options = ( + loggedInUser: CometChat.User, + message: CometChat.BaseMessage, + group?: CometChat.Group + ) => { + const defaultOptions: any = + CometChatUIKit.getDataSource().getMessageOptions(loggedInUser, message, group); + const myView: any = new CometChatActionsIcon({ + id: "refresh", + title: "Refresh", + iconURL: "", + onClick: () => { /* custom logic */ }, + }); + defaultOptions.splice(1, 0, myView); + return defaultOptions; + }; } - return templates; + return t; }); - setTemplates(template); + setTemplates(modified); }, []); - const formatTime = (timestamp: number): string => { - const date = new Date(timestamp * 1000); // Convert to milliseconds - const hours = date.getHours(); - const minutes = date.getMinutes(); - const period = hours >= 12 ? "PM" : "AM"; - const formattedHours = hours % 12 || 12; - const formattedMinutes = minutes < 10 ? "0" + minutes : minutes; - return `${formattedHours}:${formattedMinutes} ${period}`; - }; - - const getStatusInfo = (message: CometChat.BaseMessage) => { - if (message instanceof CometChat.TextMessage) { - const timestamp = message.getSentAt(); - const formattedTime = formatTime(timestamp); - return
{formattedTime}
; - } else { - return null; - } - }; + if (!chatGroup) return null; - return ( -
- {chatGroup && ( - - )} -
- ); -}; - -export { CustomMessageTemplate }; -``` - -
- - -```js -import React, { useEffect, useState } from "react"; -import { CometChatMessageList, CometChatUIKit, CometChatUIKitConstants } from '@cometchat/chat-uikit-react'; -import { CometChat } from "@cometchat/chat-sdk-javascript"; - -const CustomMessageTemplate = () => { - const [templates, setTemplates] = React.useState([]); - const [chatGroup, setChatGroup] = React.useState(); - - useEffect(() => { - CometChat.getGroup("guid").then((group) => { - setChatGroup(group); - }) - - let definedTemplates = CometChatUIKit.getDataSource().getAllMessageTemplates(); - const template = definedTemplates.map((templates) => { - if (templates.type === CometChatUIKitConstants.MessageTypes.text && - templates.category === CometChatUIKitConstants.MessageCategory.message) { - templates.statusInfoView = (message) => getStatusInfo(message) - return templates; - } - return templates - }) - setTemplates(template); - }, []); - - const formatTime = (timestamp) => { - const date = new Date(timestamp * 1000); // Convert to milliseconds - const hours = date.getHours(); - const minutes = date.getMinutes(); - const period = hours >= 12 ? 'PM' : 'AM'; - const formattedHours = hours % 12 || 12; - const formattedMinutes = minutes < 10 ? '0' + minutes : minutes; - return `${formattedHours}:${formattedMinutes} ${period}`; - }; - - const getStatusInfo = (message) => { - if (message instanceof CometChat.TextMessage) { - const timestamp = message.getSentAt(); - const formattedTime = formatTime(timestamp); - return ( -
- {formattedTime} -
- ); - } else { - return null; - } - }; - - return ( -
- {chatGroup && } -
- ); -}; - -export { CustomMessageTemplate }; -``` - -
- - -```css -.status-info { - display: flex; - width: 57px; - height: 24px; - justify-content: flex-end; - align-items: center; - border-radius: 1000px; - color: #727272; - text-align: right; - font: 400 10px/120% Roboto; - font-style: normal; -} - -.cometchat .cometchat-message-bubble__body { - background: none; -} - -.cometchat .cometchat-message-bubble .cometchat-text-bubble { - padding: 8px; + return ; } ``` - - -
- -#### ReplyView - -The `replyView` method of MessageTemplate allows you to add a reply view to your message bubbles. In the example below, we will style the existing reply view in the MessageList. - -

Default Reply View

- - Default Reply View - +### New template for a custom message type -

Custom Reply View

- Custom Reply View + - - - -```ts -import React, { useEffect, useState } from "react"; +```tsx +import { useState, useEffect } from "react"; import { - CometChatMessageList + CometChatMessageList, + CometChatUIKit, + CometChatUIKitConstants, + CometChatMessageTemplate, } from "@cometchat/chat-uikit-react"; import { CometChat } from "@cometchat/chat-sdk-javascript"; -const CustomMessageTemplate = () => { - const [chatGroup, setChatGroup] = React.useState(); +function NewTemplateDemo() { + const [chatGroup, setChatGroup] = useState(); + const [templates, setTemplates] = useState([]); useEffect(() => { - CometChat.getGroup("guid").then((group) => { - setChatGroup(group); + CometChat.getGroup("guid").then((group) => setChatGroup(group)); + + const definedTemplates = CometChatUIKit.getDataSource().getAllMessageTemplates(); + const CUSTOM_MESSAGE_TYPE = "customType"; + const customTemplate = new CometChatMessageTemplate({ + type: CUSTOM_MESSAGE_TYPE, + category: CometChatUIKitConstants.MessageCategory.custom, + contentView: (message: CometChat.BaseMessage) => ( +
Custom: {JSON.stringify(message.getData())}
+ ), }); + definedTemplates.push(customTemplate); + setTemplates(definedTemplates); }, []); + const getMessageRequestBuilder = () => { + const CUSTOM_MESSAGE_TYPE = "customType"; + const categories = CometChatUIKit.getDataSource().getAllMessageCategories(); + categories.push(CometChatUIKitConstants.MessageCategory.custom); + const types = CometChatUIKit.getDataSource().getAllMessageTypes(); + types.push(CUSTOM_MESSAGE_TYPE); + return new CometChat.MessagesRequestBuilder() + .setCategories(categories) + .setTypes(types) + .hideReplies(true) + .setLimit(30); + }; + + if (!chatGroup) return null; + return ( -
- {chatGroup && ( - - )} -
+ ); -}; - -export { CustomMessageTemplate }; +} ``` -
- - -```js -import React, { useEffect, useState } from "react"; -import { CometChatMessageList } from '@cometchat/chat-uikit-react'; -import { CometChat } from "@cometchat/chat-sdk-javascript"; - -const CustomMessageTemplate = () => { - const [chatGroup, setChatGroup] = React.useState(); - - useEffect(() => { - CometChat.getGroup("guid").then((group) => { - setChatGroup(group); - }) - }, []); - - return ( -
- {chatGroup && } -
- ); -}; +--- -export { CustomMessageTemplate }; -``` +## Styling -
+`CometChatMessageTemplate` renders inside `.cometchat-message-bubble`. Style individual bubble sections using CSS: - ```css -.cometchat - .cometchat-message-bubble-outgoing - .cometchat-message-bubble__body { - --cometchat-primary-color: #f76808; - --cometchat-extended-primary-color-700: rgba(251, 251, 251, 0.192); +.cometchat .cometchat-message-bubble__body { + /* content area overrides */ } -.cometchat .cometchat-message-bubble-incoming .bubble-view{ - --cometchat-primary-color: #f76808; +.cometchat .cometchat-message-bubble__body-footer-view { + /* footer area overrides */ } -.cometchat-message-composer__header .composer-view{ - --cometchat-primary-color: #f76808; +.cometchat .cometchat-message-bubble__body-header-view { + /* header area overrides */ } ``` - - -
- -#### Options - -The `options` method in the MessageTemplate allows you to customize the options that appear in the action sheet when a message is long-pressed. By default, CometChat UI Kit provides a set of options like "Thread Reply", "Copy" ,"Edit", and "Delete". - -However, if you wish to override or modify these options, you can use the `options` method and pass a list of `CometChatActionsIcon`. This list of options will replace the default set. - - - - - - - -```ts -import React, { useEffect, useState } from "react"; -import { - CometChatMessageList, - CometChatUIKit, - CometChatUIKitConstants, - CometChatMessageTemplate, - CometChatActionsIcon, -} from "@cometchat/chat-uikit-react"; -import { CometChat } from "@cometchat/chat-sdk-javascript"; - -const CustomMessageTemplate = () => { - const [templates, setTemplates] = useState( - [] - ); - const [chatGroup, setChatGroup] = useState(); +--- - useEffect(() => { - CometChat.getGroup("guid").then((group) => { - setChatGroup(group); - }); +## Accessibility - let definedTemplates: CometChatMessageTemplate[] = - CometChatUIKit.getDataSource().getAllMessageTemplates(); - const template = definedTemplates.map((templates) => { - if ( - templates.type === CometChatUIKitConstants.MessageTypes.text && - templates.category === CometChatUIKitConstants.MessageCategory.message - ) { - templates.options = ( - loggedInUser: CometChat.User, - message: CometChat.BaseMessage, - group?: CometChat.Group - ) => getCustomOptions(loggedInUser, message, chatGroup); - return templates; - } - return templates; - }); - setTemplates(template); - }, []); +Message templates render inside `CometChatMessageList`, which handles keyboard navigation and focus management. Custom views returned from template functions inherit the bubble's focus and ARIA context. Ensure custom content includes appropriate `aria-label` attributes when visual-only indicators are used. - const getCustomOptions = ( - loggedInUser: CometChat.User, - message: CometChat.BaseMessage, - group?: CometChat.Group - ) => { - const defaultOptions: any = - CometChatUIKit.getDataSource().getMessageOptions( - loggedInUser, - message, - chatGroup - ); - const myView: any = new CometChatActionsIcon({ - id: "refresh", - title: "Refresh", - iconURL: "", // Add your custom icon URL - onClick: () => { - /** Add your custom on click logic */ - }, - }); - defaultOptions.splice(1, 0, myView); - return defaultOptions; - }; +--- - return ( -
- {chatGroup && ( - - )} -
- ); -}; +--- -export { CustomMessageTemplate }; -``` +## Properties -
+### bubbleView - -```js -import React, { useEffect, useState } from "react"; -import { - CometChatMessageList, - CometChatUIKit, - CometChatUIKitConstants, - CometChatActionsIcon, -} from "@cometchat/chat-uikit-react"; -import { CometChat } from "@cometchat/chat-sdk-javascript"; +| Key | Value | +| --- | --- | +| Type | `((message: CometChat.BaseMessage, alignment: MessageBubbleAlignment) => Element \| JSX.Element \| null) \| null` | +| Default | `null` | -const CustomMessageTemplate = () => { - const [templates, setTemplates] = useState([]); - const [chatGroup, setChatGroup] = useState(); +Replaces the entire message bubble. When set, `headerView`, `contentView`, `footerView`, `bottomView`, `statusInfoView`, and `replyView` are ignored for that template. - useEffect(() => { - CometChat.getGroup("guid").then((group) => { - setChatGroup(group); - }); +--- - let definedTemplates = - CometChatUIKit.getDataSource().getAllMessageTemplates(); - const template = definedTemplates.map((templates) => { - if ( - templates.type === CometChatUIKitConstants.MessageTypes.text && - templates.category === CometChatUIKitConstants.MessageCategory.message - ) { - templates.options = (loggedInUser, message, group) => - getCustomOptions(loggedInUser, message, chatGroup); - return templates; - } - return templates; - }); - setTemplates(template); - }, []); +### bottomView - const getCustomOptions = (loggedInUser, message, group) => { - const defaultOptions = CometChatUIKit.getDataSource().getMessageOptions( - loggedInUser, - message, - chatGroup - ); - const myView = new CometChatActionsIcon({ - id: "refresh", - title: "Refresh", - iconURL: "", // Add your custom icon URL - onClick: () => { - /** Add your custom on click logic */ - }, - }); - defaultOptions.splice(1, 0, myView); - return defaultOptions; - }; +| Key | Value | +| --- | --- | +| Type | `((message: CometChat.BaseMessage, alignment: MessageBubbleAlignment) => Element \| JSX.Element \| null) \| null` | +| Default | `null` | - return ( -
- {chatGroup && ( - - )} -
- ); -}; +Custom bottom section below the content area. Default renders link previews or "load more" for long messages. -export { CustomMessageTemplate }; -``` +--- -
+### category - -```css -#refresh.cometchat-menu-list__menu .cometchat-menu-list__sub-menu-item-title { - overflow: hidden; - color: #6852d6; - font: 400 14px/16.8px Roboto; - font-style: italic; -} +| Key | Value | +| --- | --- | +| Type | `string` | +| Default | `""` | -#refresh.cometchat-menu-list__menu - .cometchat-menu-list__sub-menu-list-item-icon { - background-color: #6852d6; -} -``` +Maps the template to a CometChat message category (e.g., `CometChatUIKitConstants.MessageCategory.message`, `CometChatUIKitConstants.MessageCategory.custom`). - - -
+--- -### New Templates +### contentView -You can create an entirely new template for custom messages is one of the powerful features of CometChat's MessageTemplate. +| Key | Value | +| --- | --- | +| Type | `((message: CometChat.BaseMessage, alignment: MessageBubbleAlignment, textFormatters?: CometChatTextFormatter[]) => Element \| JSX.Element \| null) \| null` | +| Default | `null` | - - - +Custom content area. Default renders text, image, video, audio, or file bubble based on message type. - - -```ts -import React, { useEffect, useState } from "react"; -import { - CometChatMessageList, - CometChatUIKit, - CometChatUIKitConstants, - CometChatMessageTemplate, - MessageReceiptUtils, - isMessageSentByMe, - Receipts, - CometChatUIKitLoginListener, -} from "@cometchat/chat-uikit-react"; -import { CometChat } from "@cometchat/chat-sdk-javascript"; -import readIcon from "../../assets/message-read.svg"; -import sentIcon from "../../assets/message-sent.svg"; -import deliveredIcon from "../../assets/message-delivered.svg"; +--- -const CustomMessageTemplate = () => { - const [templates, setTemplates] = React.useState( - [] - ); - const [chatGroup, setChatGroup] = React.useState(); +### footerView - useEffect(() => { - CometChat.getGroup("guid").then((group) => { - setChatGroup(group); - }); +| Key | Value | +| --- | --- | +| Type | `((message: CometChat.BaseMessage, alignment: MessageBubbleAlignment) => Element \| JSX.Element \| null) \| null` | +| Default | `null` | - let definedTemplates = - CometChatUIKit.getDataSource().getAllMessageTemplates(); - const CUSTOM_MESSAGE_TYPE = "customType"; - let customMessageTemplate = new CometChatMessageTemplate({ - type: CUSTOM_MESSAGE_TYPE, - category: CometChatUIKitConstants.MessageCategory.custom, - contentView: (message: CometChat.BaseMessage) => getContentView(message), - }); - definedTemplates.push(customMessageTemplate); - setTemplates(definedTemplates); - }, []); +Custom footer below the content area. Default renders reactions. - const formatTime = (timestamp: number): string => { - const date = new Date(timestamp * 1000); // Convert to milliseconds - const hours = date.getHours(); - const minutes = date.getMinutes(); - const period = hours >= 12 ? "PM" : "AM"; - const formattedHours = hours % 12 || 12; - const formattedMinutes = minutes < 10 ? "0" + minutes : minutes; - return `${formattedHours}:${formattedMinutes} ${period}`; - }; +--- - const getContentView = (message: CometChat.BaseMessage) => { - const isSentByMe = isMessageSentByMe( - message, - CometChatUIKitLoginListener.getLoggedInUser()! - ); - - const receipt = MessageReceiptUtils.getReceiptStatus(message); - let status = sentIcon; - - if (receipt === Receipts.delivered) { - status = deliveredIcon; - } else if (receipt === Receipts.read) { - status = readIcon; - } else { - status = sentIcon; - } - - return ( -
-
- -
- {formatTime(message.getSentAt())} - {isSentByMe && ( - - )} -
-
-
-
Add Contact
-
Message
-
-
- ); - }; +### headerView - const getMessageRequestBuilder = () => { - const CUSTOM_MESSAGE_TYPE = "customType"; - let categories = CometChatUIKit.getDataSource().getAllMessageCategories(); - categories.push(CometChatUIKitConstants.MessageCategory.custom); - let types = CometChatUIKit.getDataSource().getAllMessageTypes(); - types.push(CUSTOM_MESSAGE_TYPE); - return new CometChat.MessagesRequestBuilder() - .setCategories(categories) - .setTypes(types) - .hideReplies(true) - .setLimit(30); - }; +| Key | Value | +| --- | --- | +| Type | `((message: CometChat.BaseMessage, alignment: MessageBubbleAlignment) => Element \| JSX.Element \| null) \| null` | +| Default | `null` | - return ( -
- {chatGroup && ( - - )} -
- ); -}; +Custom header above the content area. Default renders sender name. -export { CustomMessageTemplate }; -``` +--- -
+### options - -```js -import React, { useEffect, useState } from "react"; -import { CometChatMessageList, CometChatUIKit, CometChatUIKitConstants, -CometChatMessageTemplate,MessageReceiptUtils,isMessageSentByMe,Receipts,CometChatUIKitLoginListener } from '@cometchat/chat-uikit-react'; -import { CometChat } from "@cometchat/chat-sdk-javascript"; -import readIcon from "../../assets/message-read.svg"; -import sentIcon from "../../assets/message-sent.svg"; -import deliveredIcon from "../../assets/message-delivered.svg"; - - -const CustomMessageTemplate = () => { - const [templates, setTemplates] = React.useState([]); - const [chatGroup, setChatGroup] = React.useState(); - - useEffect(() => { - CometChat.getGroup("guid").then((group) => { - setChatGroup(group); - }) - - let definedTemplates = CometChatUIKit.getDataSource().getAllMessageTemplates(); - const CUSTOM_MESSAGE_TYPE = "customType"; - let customMessageTemplate = new CometChatMessageTemplate({ - type: CUSTOM_MESSAGE_TYPE, - category: CometChatUIKitConstants.MessageCategory.custom, - contentView: (message) => getContentView(message), - }); - definedTemplates.push(customMessageTemplate); - setTemplates(definedTemplates); - }, []); - - const formatTime = (timestamp) => { - const date = new Date(timestamp * 1000); // Convert to milliseconds - const hours = date.getHours(); - const minutes = date.getMinutes(); - const period = hours >= 12 ? 'PM' : 'AM'; - const formattedHours = hours % 12 || 12; - const formattedMinutes = minutes < 10 ? '0' + minutes : minutes; - return `${formattedHours}:${formattedMinutes} ${period}`; - }; - - const getContentView = (message) => { - const isSentByMe = isMessageSentByMe( - message, - CometChatUIKitLoginListener.getLoggedInUser()! - ); - - const receipt = MessageReceiptUtils.getReceiptStatus(message); - let status = sentIcon; - - if (receipt === Receipts.delivered) { - status = deliveredIcon; - } else if (receipt === Receipts.read) { - status = readIcon; - } else { - status = sentIcon; - } +| Key | Value | +| --- | --- | +| Type | `(loggedInUser: CometChat.User, message: CometChat.BaseMessage, group?: CometChat.Group) => CometChatMessageOption[]` | +| Default | SDK default options | - return ( -
-
- -
- {formatTime(message.getSentAt())} - {isSentByMe && ( - - )} -
-
-
-
Add Contact
-
Message
-
-
- ); - }; - - const getMessageRequestBuilder = () => { - const CUSTOM_MESSAGE_TYPE = "customType"; - let categories = CometChatUIKit.getDataSource().getAllMessageCategories(); - categories.push(CometChatUIKitConstants.MessageCategory.custom); - let types = CometChatUIKit.getDataSource().getAllMessageTypes(); - types.push(CUSTOM_MESSAGE_TYPE); - return new CometChat.MessagesRequestBuilder().setCategories(categories).setTypes(types).hideReplies(true).setLimit(30); - } - - return ( -
- {chatGroup && } -
- ); -}; +Returns the list of action sheet items for long-press on a message bubble. -export { CustomMessageTemplate }; -``` +--- -
+### replyView - -```css -.content-view { - display: flex; - flex-direction: column; - gap: 4px; -} +| Key | Value | +| --- | --- | +| Type | `((message: CometChat.BaseMessage, alignment?: MessageBubbleAlignment, onReplyViewClicked?: (msg: CometChat.BaseMessage) => void, textFormatters?: CometChatTextFormatter[]) => Element \| JSX.Element \| null) \| null` | +| Default | `null` | -.content-view .cometchat-list-item { - background: none; -} +Custom reply preview above the content area. -.content-view .cometchat-list-item__body-title { - overflow: hidden; - color: #f9f8fd; - text-overflow: ellipsis; - font: 500 14px/16.8px roboto; - font-style: normal; -} +--- -.cometchat-message-bubble-incoming .cometchat-list-item__body-title, -.cometchat-message-bubble-incoming .content-view__header-time, -.cometchat-message-bubble-incoming .content-view__footer-message, -.cometchat-message-bubble-incoming .content-view__footer-add-contact { - color: #141414; -} +### statusInfoView -.cometchat-message-bubble-incoming .content-view__footer { - border-top: 1px solid #dcdcdc; -} +| Key | Value | +| --- | --- | +| Type | `((message: CometChat.BaseMessage, alignment: MessageBubbleAlignment, hideReceipts?: boolean, messageSentAtDateTimeFormat?: CalendarObject, showError?: boolean) => Element \| JSX.Element \| null) \| null` | +| Default | `null` | -.cometchat-message-bubble-incoming .content-view__footer-add-contact { - border-right: 1px solid #dcdcdc; -} +Custom status info area. Default renders receipt icon and timestamp. -.content-view__header-time { - display: flex; - justify-content: end; - gap: 4px; - color: #f9f8fd; - text-align: right; - font: 400 10px/12px roboto; - font-style: normal; -} +--- -.content-view__footer { - border-top: 1px solid #7965db; - display: flex; - height: 40px; - justify-content: center; - align-items: center; - align-self: stretch; -} +### type -.content-view__footer-add-contact { - width: 50%; - height: 100%; - border-right: 1px solid #7965db; - display: flex; - align-items: center; - justify-content: center; - color: #f9f8fd; - font: 500 14px/16.8px roboto; - font-style: normal; -} +| Key | Value | +| --- | --- | +| Type | `string` | +| Default | — (required) | -.content-view__footer-message { - width: 50%; - height: 100%; - display: flex; - align-items: center; - justify-content: center; - color: #f9f8fd; - font: 500 14px/16.8px roboto; - font-style: normal; -} -``` - - +Maps the template to a CometChat message type (e.g., `CometChatUIKitConstants.MessageTypes.text`, `CometChatUIKitConstants.MessageTypes.image`). -
+--- diff --git a/ui-kit/react/methods.mdx b/ui-kit/react/methods.mdx index 0be19fef4..fbc1f8f9a 100644 --- a/ui-kit/react/methods.mdx +++ b/ui-kit/react/methods.mdx @@ -1,33 +1,51 @@ --- title: "Methods" +description: "Reference for CometChat React UI Kit methods including init, login, logout, and message-sending wrappers." --- + + +| Field | Value | +| --- | --- | +| Package | `@cometchat/chat-uikit-react` | +| Import | `import { CometChatUIKit } from "@cometchat/chat-uikit-react";` | +| Init | `CometChatUIKit.init(UIKitSettings)` | +| Login (dev) | `CometChatUIKit.login("UID")` | +| Login (prod) | `CometChatUIKit.loginWithAuthToken("AUTH_TOKEN")` | +| Other methods | `CometChatUIKit.logout()`, `CometChatUIKit.getLoggedinUser()`, `CometChatUIKit.createUser(user)`, `CometChatUIKit.updateUser(user)` | +| Send messages | `CometChatUIKit.sendTextMessage()`, `CometChatUIKit.sendMediaMessage()`, `CometChatUIKit.sendCustomMessage()` | +| Note | Use these wrapper methods instead of raw SDK calls — they manage internal UI Kit eventing | + + + ## Overview -The UI Kit's core function is to extend the [Chat SDK](/sdk/javascript/overview), essentially translating the raw data and functionality provided by the underlying methods into visually appealing and easy-to-use UI components. +The UI Kit wraps the [Chat SDK](/sdk/javascript/overview) methods to manage internal eventing and keep UI components synchronized. Use these wrapper methods instead of raw SDK calls. -To effectively manage and synchronize the UI elements and data across all components in the UI Kit, we utilize internal events. These internal events enable us to keep track of changes in real time and ensure that the UI reflects the most current state of data. + +`CometChatUIKit.init(UIKitSettings)` must be called before rendering any UI Kit components or calling any SDK methods. Initialization must complete before login. + -The CometChat UI Kit has thoughtfully encapsulated the critical [Chat SDK](/sdk/javascript/overview) methods within its wrapper to efficiently manage internal eventing. This layer of abstraction simplifies interaction with the underlying CometChat SDK, making it more user-friendly for developers. + +Auth Key is for development/testing only. In production, generate Auth Tokens on the server using the REST API and pass them to the client via `loginWithAuthToken()`. Never expose Auth Keys in production client code. + ## Methods -You can access the methods using the `CometChatUIKit` class. This class provides access to all the public methods exposed by the CometChat UI Kit. +All methods are accessed via the `CometChatUIKit` class. ### Init -This method initializes the settings required for [CometChat JavaScript SDK](/sdk/javascript/overview). First, ensure UIKitSettings is set and then call the `init()` method on the app startup. +Initializes the [CometChat JavaScript SDK](/sdk/javascript/overview). Must be called on app startup before any other UI Kit method. - -Make sure you replace the **APP\_ID**, **REGION** and **AUTH\_KEY** with your CometChat App ID, Region and Auth Key in the below code. The `Auth Key` is an optional property of the `UIKitSettings` Class. It is intended for use primarily during proof-of-concept (POC) development or in the early stages of application development. You can use the [Auth Token](#login-using-auth-token) method to log in securely. - +Replace `APP_ID`, `REGION`, and `AUTH_KEY` with values from the CometChat Dashboard. `Auth Key` is optional — use [Auth Token](#login-using-auth-token) for production. -```js -import { UIKitSettingsBuilder } from "@cometchat/uikit-shared"; //import shared package +```js lines highlight={4-6} +import { CometChatUIKit, UIKitSettingsBuilder } from "@cometchat/chat-uikit-react"; const COMETCHAT_CONSTANTS = { APP_ID: "APP_ID", // Replace with your App ID @@ -57,11 +75,11 @@ CometChatUIKit.init(UIKitSettings)?.then(() => { ### Setting Session Storage Mode -If you want to use session storage instead of the default local storage, you can configure it during initialization: +To use session storage instead of the default local storage, configure it during initialization: -```js +```js lines highlight={5-7} import { CometChat } from "@cometchat/chat-sdk-javascript"; import { UIKitSettingsBuilder } from "@cometchat/chat-uikit-react"; @@ -89,7 +107,7 @@ CometChatUIKit.init(UIKitSettings)?.then(() => { -```ts +```ts lines highlight={5-7} import { CometChat } from "@cometchat/chat-sdk-javascript"; import { UIKitSettingsBuilder } from "@cometchat/chat-uikit-react"; @@ -119,11 +137,11 @@ CometChatUIKit.init(UIKitSettings)?.then(() => { ### Get Logged In User -You can use this method to check if there is any existing session in the SDK. This method should return the details of the logged-in user. +Checks for an existing session in the SDK. Returns the logged-in user details or `null`. -```js +```js lines import { CometChatUIKit } from "@cometchat/chat-uikit-react"; //import uikit package CometChatUIKit.getLoggedinUser() @@ -141,11 +159,11 @@ CometChatUIKit.getLoggedinUser() ### Login using Auth Key -This simple authentication procedure is useful when you are creating a POC or if you are in the development phase. For production apps, we suggest you use [AuthToken](#login-using-auth-token) instead of Auth Key. +Simple authentication for development/POC. For production, use [Auth Token](#login-using-auth-token). -```js +```js lines highlight={3} import { CometChatUIKit } from "@cometchat/chat-uikit-react"; //import uikit package const UID = "UID"; @@ -170,7 +188,7 @@ CometChatUIKit.getLoggedinUser() -```ts +```ts lines highlight={3} import { CometChatUIKit } from "@cometchat/chat-uikit-react"; //import uikit package const UID: string = "UID"; @@ -200,7 +218,7 @@ CometChatUIKit.getLoggedinUser() ### Login using Auth Token -This advanced authentication procedure does not use the Auth Key directly in your client code thus ensuring safety. +Production-safe authentication that does not expose the Auth Key in client code. 1. [Create a User](https://api-explorer.cometchat.com/reference/creates-user) via the CometChat API when the user signs up in your app. 2. [Create an Auth Token](https://api-explorer.cometchat.com/reference/create-authtoken) via the CometChat API for the new user and save the token in your database. @@ -208,7 +226,7 @@ This advanced authentication procedure does not use the Auth Key directly in you -```js +```js lines highlight={3} import { CometChatUIKit } from "@cometchat/chat-uikit-react"; //import uikit package const authToken = "AUTH_TOKEN"; @@ -234,12 +252,12 @@ CometChatUIKit.getLoggedinUser() -```ts +```ts lines highlight={3} import { CometChatUIKit } from "@cometchat/chat-uikit-react"; //import uikit package const authToken: string = "AUTH_TOKEN"; -CometChat.getLoggedinUser() +CometChatUIKit.getLoggedinUser() .then((user: CometChat.User) => { if (!user) { //Login user @@ -262,11 +280,11 @@ CometChat.getLoggedinUser() ### Logout -This method is used to end the user session of the logged-in user +Ends the current user session. -```js +```js lines import { CometChatUIKit } from "@cometchat/chat-uikit-react"; //import uikit package CometChatUIKit.logout(); @@ -280,11 +298,11 @@ CometChatUIKit.logout(); ### Create user -This method takes a `User` object and the `Auth Key` as input parameters and returns the created `User` object if the request is successful. +Takes a `User` object and Auth Key, returns the created `User` object. -```js +```js lines highlight={4-6} import { CometChat } from "@cometchat/chat-sdk-javascript"; //import sdk package import { CometChatUIKit } from "@cometchat/chat-uikit-react"; //import uikit package @@ -311,7 +329,7 @@ CometChatUIKit.createUser(user, authKey) -```ts +```ts lines highlight={4-6} import { CometChat } from "@cometchat/chat-sdk-javascript"; //import sdk package import { CometChatUIKit } from "@cometchat/chat-uikit-react"; //import uikit package @@ -343,11 +361,11 @@ CometChatUIKit.createUser(user, authKey) ### Update user -This method takes a `User` object and the `Auth Key` as inputs and returns the updated `User` object on the successful execution of the request. +Takes a `User` object and Auth Key, returns the updated `User` object. -```js +```js lines highlight={4-6} import { CometChat } from "@cometchat/chat-sdk-javascript"; //import sdk package import { CometChatUIKit } from "@cometchat/chat-uikit-react"; //import uikit package @@ -367,7 +385,7 @@ CometChatUIKit.updateUser(user, authKey) -```ts +```ts lines highlight={4-6} import { CometChat } from "@cometchat/chat-sdk-javascript"; //import sdk package import { CometChatUIKit } from "@cometchat/chat-uikit-react"; //import uikit package @@ -394,11 +412,11 @@ CometChatUIKit.updateUser(user, authKey) #### Text message -This method sends a text message in a 1:1 or group chat. You need to pass a `TextMessage` object to it. +Sends a text message in a 1:1 or group chat. Takes a `TextMessage` object. -```tsx +```tsx lines highlight={5-6} import { CometChat } from "@cometchat/chat-sdk-javascript"; //import sdk package import { CometChatUIKit } from "@cometchat/chat-uikit-react"; //import uikit package import { CometChatUIKitConstants } from "@cometchat/uikit-resources"; //import shared package @@ -422,7 +440,7 @@ CometChatUIKit.sendTextMessage(textMessage) -```tsx +```tsx lines highlight={5-6} import { CometChat } from "@cometchat/chat-sdk-javascript"; //import sdk package import { CometChatUIKit } from "@cometchat/chat-uikit-react"; //import uikit package import { CometChatUIKitConstants } from "@cometchat/uikit-resources"; //import shared package @@ -451,17 +469,15 @@ CometChatUIKit.sendMessage(textMessage) #### Media message -This method sends a media message in a 1:1 or group chat. You need to pass a `MediaMessage` object to it. +Sends a media message in a 1:1 or group chat. Takes a `MediaMessage` object. - -Make sure you replace the `INPUT FILE OBJECT` with the actual [file](https://developer.mozilla.org/en-US/docs/Web/API/File). - +Replace `INPUT FILE OBJECT` with the actual [File](https://developer.mozilla.org/en-US/docs/Web/API/File) object. -```tsx +```tsx lines highlight={5} import { CometChat } from "@cometchat/chat-sdk-javascript"; //import sdk package import { CometChatUIKit } from "@cometchat/chat-uikit-react"; //import uikit package import { CometChatUIKitConstants } from "@cometchat/uikit-resources"; //import shared package @@ -486,7 +502,7 @@ CometChatUIKit.sendMediaMessage(mediaMessage) -```tsx +```tsx lines highlight={5} import { CometChat } from "@cometchat/chat-sdk-javascript"; //import sdk package import { CometChatUIKit } from "@cometchat/chat-uikit-react"; //import uikit package import { CometChatUIKitConstants } from "@cometchat/uikit-resources"; //import shared package @@ -516,11 +532,11 @@ CometChatUIKit.sendMediaMessage(mediaMessage) #### Custom message -This method allows you to send custom messages which are neither text nor media messages. +Sends a custom message (neither text nor media) in a 1:1 or group chat. Takes a `CustomMessage` object. -```tsx +```tsx lines highlight={5,7,8} import { CometChat } from "@cometchat/chat-sdk-javascript"; //import sdk package import { CometChatUIKit } from "@cometchat/chat-uikit-react"; //import uikit package import { CometChatUIKitConstants } from "@cometchat/uikit-resources"; //import shared package @@ -549,7 +565,7 @@ CometChatUIKit.sendCustomMessage(customMessage) -```tsx +```tsx lines highlight={5,7,8} import { CometChat } from "@cometchat/chat-sdk-javascript"; //import sdk package import { CometChatUIKit } from "@cometchat/chat-uikit-react"; //import uikit package import { CometChatUIKitConstants } from "@cometchat/uikit-resources"; //import shared package diff --git a/ui-kit/react/next-conversation.mdx b/ui-kit/react/next-conversation.mdx index 1d8800f66..83701d95d 100644 --- a/ui-kit/react/next-conversation.mdx +++ b/ui-kit/react/next-conversation.mdx @@ -1,39 +1,41 @@ --- title: "Building A Conversation List + Message View" sidebarTitle: "Conversation List + Message View" +description: "Build a two-panel conversation list + message view layout in Next.js with CometChat UI Kit." --- -The **Conversation List + Message View** layout offers a seamless **two-panel chat interface**, commonly used in modern messaging applications like **WhatsApp Web, Slack, and Microsoft Teams**. + +- **Package:** `@cometchat/chat-uikit-react` +- **Framework:** Next.js +- **Key components:** `CometChatConversations` + `CometChatMessageList` +- **Required setup:** `CometChatUIKit.init(UIKitSettings)` then `CometChatUIKit.login("UID")` +- **Parent guide:** [Next.js Integration](/ui-kit/react/next-js-integration) + -This design enables users to switch between conversations effortlessly while keeping the chat window open, ensuring a **smooth, real-time messaging experience**. +Two-panel chat layout: conversation list on the left, active chat on the right. Supports 1:1 and group conversations with real-time updates. [](https://link.cometchat.com/next-conversation-list-message) -> **Tip:** You can **fork** the sandbox, insert your **CometChat credentials** (App ID, Region, Auth Key.) in the code, and immediately preview how the UI and messages respond in real time. - -*** - -## **User Interface Overview** +## User Interface Overview -This layout is structured into three key sections: - -1. **Sidebar (Conversation List)** – Displays active conversations, including users and groups. -2. **Message View** – Shows chat messages for the selected conversation in real-time. -3. **Message Composer** – Provides an input field for typing and sending messages, along with support for media, emojis, and reactions. +Three sections: -*** +1. Sidebar (Conversation List) — active conversations (users and groups) +2. Message View — messages for the selected conversation +3. Message Composer — text input with media, emoji, and reaction support -## **Step-by-Step Guide** +## Step-by-Step Guide -### **Step 1: Create Sidebar** + + Let's create the `Sidebar` component which will render different conversations. -#### **Folder Structure** +#### Folder Structure Create a `CometChatSelector` folder inside your `src/app` directory and add the following files: @@ -44,7 +46,7 @@ src/app/ │ ├── CometChatSelector.css ``` -#### **Download the Icon** +#### Download the Icon These icons are available in the **CometChat UI Kit assets folder**. You can find them at:\ 🔗 [GitHub Assets Folder](https://github.com/cometchat/cometchat-uikit-react/tree/v6/sample-app/src/assets) @@ -52,48 +54,37 @@ These icons are available in the **CometChat UI Kit assets folder**. You can fin -```tsx CometChatSelector.tsx +```tsx CometChatSelector.tsx lines import { useEffect, useState } from "react"; import { Conversation, Group, User } from "@cometchat/chat-sdk-javascript"; import { CometChatConversations, CometChatUIKitLoginListener } from "@cometchat/chat-uikit-react"; import { CometChat } from '@cometchat/chat-sdk-javascript'; import "./CometChatSelector.css"; - -// Define props interface for component interface SelectorProps { onSelectorItemClicked?: (input: User | Group | Conversation, type: string) => void; } - -// CometChatSelector component definition export const CometChatSelector = (props: SelectorProps) => { const { - onSelectorItemClicked = () => { }, // Default function if no prop is provided + onSelectorItemClicked = () => { }, } = props; - - // State to store the currently logged-in user const [loggedInUser, setLoggedInUser] = useState(); - - // State to track the currently selected item (conversation, user, group, or call) const [activeItem, setActiveItem] = useState< CometChat.Conversation | CometChat.User | CometChat.Group | CometChat.Call | undefined >(); useEffect(() => { - // Retrieve the logged-in user from CometChat's login listener let loggedInUser = CometChatUIKitLoginListener.getLoggedInUser(); setLoggedInUser(loggedInUser); - }, [CometChatUIKitLoginListener?.getLoggedInUser()]); // Dependency array to trigger effect when user changes + }, [CometChatUIKitLoginListener?.getLoggedInUser()]); return ( - <> - {/* Render CometChatConversations only if a user is logged in */} - {loggedInUser && ( + <> {loggedInUser && ( <> { - setActiveItem(e); // Update the selected item state - onSelectorItemClicked(e, "updateSelectedItem"); // Trigger callback with selected item + setActiveItem(e); + onSelectorItemClicked(e, "updateSelectedItem"); }} /> @@ -107,66 +98,54 @@ export const CometChatSelector = (props: SelectorProps) => { -```css CometChatSelector.css -/* Style for the icon in the header menu of the conversation list */ +```css CometChatSelector.css lines .selector-wrapper .cometchat-conversations .cometchat-list__header-menu .cometchat-button__icon { background: var(--cometchat-icon-color-primary); } -/* Change background color of icon on hover */ .cometchat-conversations .cometchat-list__header-menu .cometchat-button__icon:hover { background: var(--cometchat-icon-color-highlight); } -/* Remove the right border from the search bar */ .cometchat-list__header-search-bar { border-right: none; } -/* Align submenu items to the left */ .cometchat .cometchat-menu-list__sub-menu-list-item { text-align: left; } -/* Set specific width and positioning for submenu list */ .cometchat .cometchat-conversations .cometchat-menu-list__sub-menu-list { width: 212px; top: 40px !important; left: 172px !important; } -/* Style the logged-in user section with a bottom border */ #logged-in-user { border-bottom: 2px solid var(--cometchat-border-color-default, #E8E8E8); } -/* Prevent cursor interaction on logged-in user menu items */ #logged-in-user .cometchat-menu-list__sub-menu-item-title, #logged-in-user .cometchat-menu-list__sub-menu-list-item { cursor: default; } -/* Style for logout icon with error color */ .cometchat-menu-list__sub-menu-list-item-icon-log-out { background-color: var(--cometchat-error-color, #F44649); } -/* Style for logout text with error color */ .cometchat-menu-list__sub-menu-item-title-log-out { color: var(--cometchat-error-color, #F44649); } -/* Allow pointer interaction on submenu items inside chat menu */ .chat-menu .cometchat .cometchat-menu-list__sub-menu-item-title { cursor: pointer; } -/* Remove shadow from submenu inside chat menu */ .chat-menu .cometchat .cometchat-menu-list__sub-menu { box-shadow: none; } -/* Style for submenu icons inside chat menu */ .chat-menu .cometchat .cometchat-menu-list__sub-menu-icon { background-color: var(--cometchat-icon-color-primary, #141414); width: 24px; @@ -178,7 +157,8 @@ export const CometChatSelector = (props: SelectorProps) => { -### **Step 2: Render Experience** + + Now we will create the `CometChatNoSSR.tsx` & `CometChatNoSSR.css` files. Here, we will initialize the CometChat UI Kit, log in a user, and build the messaging experience using `CometChatMessageHeader`, `CometChatMessageList`, and `CometChatMessageComposer` components. @@ -192,7 +172,7 @@ src/ -```tsx CometChatNoSSR.tsx +```tsx CometChatNoSSR.tsx lines highlight={15-17, 20} import React, { useEffect, useState } from "react"; import { CometChatMessageComposer, @@ -204,40 +184,31 @@ import { import { CometChat } from "@cometchat/chat-sdk-javascript"; import { CometChatSelector } from "../CometChatSelector/CometChatSelector"; import "./CometChatNoSSR.css"; - -// Constants for CometChat configuration const COMETCHAT_CONSTANTS = { APP_ID: "", REGION: "", AUTH_KEY: "", }; -// Functional Component +const UID = "cometchat-uid-1"; // Replace with your actual UID const CometChatNoSSR: React.FC = () => { - // State to store the logged-in user const [user, setUser] = useState(undefined); - // State to store selected user or group const [selectedUser, setSelectedUser] = useState(undefined); const [selectedGroup, setSelectedGroup] = useState(undefined); useEffect(() => { - // Initialize UIKit settings const UIKitSettings = new UIKitSettingsBuilder() .setAppId(COMETCHAT_CONSTANTS.APP_ID) .setRegion(COMETCHAT_CONSTANTS.REGION) .setAuthKey(COMETCHAT_CONSTANTS.AUTH_KEY) .subscribePresenceForAllUsers() .build(); - - // Initialize CometChat UIKit CometChatUIKit.init(UIKitSettings) ?.then(() => { console.log("Initialization completed successfully"); - // Check if user is already logged in CometChatUIKit.getLoggedinUser().then((loggedInUser) => { if (!loggedInUser) { - // Perform login if no user is logged in - CometChatUIKit.login("cometchat-uid-1") + CometChatUIKit.login(UID) .then((user) => { console.log("Login Successful", { user }); setUser(user); @@ -253,17 +224,13 @@ const CometChatNoSSR: React.FC = () => { }, []); return user ? ( -
- {/* Sidebar with conversation list */} -
+
{ let item = activeItem; - // Extract the conversation participant if (activeItem instanceof CometChat.Conversation) { item = activeItem.getConversationWith(); } - // Update states based on the type of selected item if (item instanceof CometChat.User) { setSelectedUser(item as CometChat.User); setSelectedGroup(undefined); @@ -276,10 +243,7 @@ const CometChatNoSSR: React.FC = () => { } }} /> -
- - {/* Message view section */} - {selectedUser || selectedGroup ? ( +
{selectedUser || selectedGroup ? (
@@ -299,38 +263,33 @@ export default CometChatNoSSR; -```css CometChatNoSSR.css -/* Layout for the main conversations and messages container */ +```css CometChatNoSSR.css lines .conversations-with-messages { display: flex; height: 100%; width: 100%; } -/* Sidebar wrapper for conversations */ .conversations-wrapper { height: 100%; - width: 480px; /* Fixed width for conversation list */ + width: 480px; overflow: hidden; display: flex; flex-direction: column; height: inherit; } -/* Hide overflow for the conversation list */ .conversations-wrapper > .cometchat { overflow: hidden; } -/* Message section layout */ .messages-wrapper { - width: calc(100% - 480px); /* Take remaining space */ + width: calc(100% - 480px); height: 100%; display: flex; flex-direction: column; } -/* Display styling for when no conversation is selected */ .empty-conversation { height: 100%; width: 100%; @@ -342,7 +301,6 @@ export default CometChatNoSSR; font: var(--cometchat-font-body-regular, 400 14px Roboto); } -/* Ensure message composer does not have rounded corners */ .cometchat .cometchat-message-composer { border-radius: 0px; } @@ -352,23 +310,22 @@ export default CometChatNoSSR; -### **Step 3: Disabling SSR for `CometChatNoSSR.tsx` in Next.js** + + In this update, we will **disable Server-Side Rendering (SSR) for `CometChatNoSSR.tsx`** while keeping the rest of the application’s SSR functionality intact. This ensures that the **CometChat UI Kit components load only on the client-side**, preventing SSR-related issues. -#### **Disabling SSR in `index.tsx`** +#### Disabling SSR in `index.tsx` Modify your `index.tsx` file to dynamically import the `CometChatNoSSR.tsx` component with `{ ssr: false }`. -```tsx index.tsx +```tsx index.tsx lines import { Inter } from "next/font/google"; import dynamic from "next/dynamic"; import '@cometchat/chat-uikit-react/css-variables.css'; const inter = Inter({ subsets: ["latin"] }); - -// Dynamically import CometChat component with SSR disabled const CometChatComponent = dynamic(() => import("../CometChatNoSSR/CometChatNoSSR"), { ssr: false, }); @@ -378,17 +335,18 @@ export default function Home() { } ``` -#### **Why disable SSR?** +#### Why disable SSR? * The CometChat UI Kit depends on browser APIs (window, document, WebSockets). * Next.js pre-renders components on the server, which can cause errors with browser-specific features. * By setting `{ ssr: false }`, we ensure that CometChatNoSSR.tsx only loads on the client. -### **Step 4: Update Global CSS** + + Next, add the following styles to global.css to ensure CometChat UI Kit is properly styled. -```css global.css +```css global.css lines :root { --background: #ffffff; --foreground: #171717; @@ -447,18 +405,47 @@ a { } ``` -### **Step 5: Run the project** + + -``` + + +```bash lines npm run dev ``` + -*** - -## **Next Steps** - -### **Enhance the User Experience** + +```bash lines +pnpm dev +``` + -* **[Advanced Customizations](/ui-kit/react/theme)** – Personalize the chat UI to align with your brand. + +```bash lines +yarn dev +``` + + -*** + + + +For prop details and customization options, see the component reference pages: [CometChatConversations](/ui-kit/react/conversations), [CometChatMessageList](/ui-kit/react/message-list), [CometChatMessageComposer](/ui-kit/react/message-composer), [CometChatMessageHeader](/ui-kit/react/message-header). + +## Next Steps + + + + Customize colors, fonts, and styles. + + + Browse all available UI components. + + + Next.js setup guide. + + + Core chat features. + + diff --git a/ui-kit/react/next-js-integration.mdx b/ui-kit/react/next-js-integration.mdx index 0d4c40aac..680aa9a2a 100644 --- a/ui-kit/react/next-js-integration.mdx +++ b/ui-kit/react/next-js-integration.mdx @@ -1,104 +1,45 @@ --- title: "Getting Started With CometChat React UI Kit For Next.js" sidebarTitle: "Integration" +description: "Step-by-step guide to integrate CometChat React UI Kit into your Next.js application with App Router support." --- -The **CometChat UI Kit for React** streamlines the integration of in-app chat functionality by providing a **comprehensive set of prebuilt UI components**. It offers seamless **theming options**, including **light and dark modes**, customizable fonts, colors, and extensive styling capabilities. + +- **Package:** `@cometchat/chat-uikit-react` — `npm install @cometchat/chat-uikit-react` +- **Required setup:** `CometChatUIKit.init(UIKitSettings)` then `CometChatUIKit.login("UID")` — must complete before rendering +- **SSR:** CometChat requires browser APIs — use `'use client'` directive or dynamic imports with `ssr: false` +- **Init code:** `new UIKitSettingsBuilder().setAppId("APP_ID").setRegion("REGION").setAuthKey("AUTH_KEY").build()` +- **Framework:** Next.js (this page) | [React.js](/ui-kit/react/react-js-integration) | [React Router](/ui-kit/react/react-router-integration) | [Astro](/ui-kit/react/astro-integration) +- **All components:** [Components Overview](/ui-kit/react/components-overview) + -With built-in support for **one-to-one and group conversations**, developers can efficiently enable chat features within their applications. Follow this guide to **quickly integrate chat functionality** using the CometChat React UI Kit. +The CometChat UI Kit for React provides prebuilt UI components for in-app chat — one-to-one and group conversations, theming (light/dark modes), and calling. This guide covers Next.js integration with App Router. -{/* - - */} + +CometChat UI Kit requires browser APIs (`window`, `WebSocket`, `document`). For Next.js, render components only on the client side using `'use client'` directive or dynamic imports with `ssr: false`. + -*** - -## **Prerequisites** - -Before installing the **CometChat UI Kit for React**, you must first **create a CometChat application** via the **[CometChat Dashboard](https://app.cometchat.com/)**. The dashboard provides all the essential chat service components, including: - -* **User Management** -* **Group Chat & Messaging** -* **Voice & Video Calling** -* **Real-time Notifications** - -> To initialize the **UI Kit**, you will need the following credentials from your **CometChat application**: -> -> 1. **App ID** -> 2. **Auth Key** -> 3. **Region** -> -> Ensure you have these details ready before proceeding with the installation and configuration. - -*** - -## **Register & Set Up CometChat** - -Follow these steps to **register on CometChat** and **set up your development environment**. +## Prerequisites -### **Step 1: Register on CometChat** +Create a CometChat application via the [CometChat Dashboard](https://app.cometchat.com/). The dashboard provides user management, group chat, voice/video calling, and real-time notifications. -To use **CometChat UI Kit**, you first need to register on the **CometChat Dashboard**. +Required credentials from the dashboard: -🔗 **[Click here to Sign Up](https://app.cometchat.com/login)** +1. App ID +2. Auth Key +3. Region -### **Step 2: Get Your Application Keys** - -After registering, create a **new app** and retrieve your **authentication details**: - -1. Navigate to **Application**, then select the **Credentials** section. - -2. Note down the following keys: - - * **App ID** - * **Auth Key** - * **Region** - - - -Each CometChat application can be integrated with a **single client app**. Users within the same application can communicate across multiple platforms, including **web and mobile**. - - +## Getting Started -### **Step 3: Set Up Your Development Environment** - -Ensure your system meets the following **prerequisites** before proceeding with integration. - -**System Requirements:** - -* **Node.js** installed on your machine. -* A code editor like **[Visual Studio Code](https://code.visualstudio.com/)** or **[Cursor](https://www.cursor.com/)**. -* **npm** or **Yarn** package manager installed. - -*** - -## **Built With** - -The CometChat UI Kit for React relies on the following technologies: - -| Technology | Description | -| ---------------------------------------------------- | ------------------------------------- | -| [Node.js](https://nodejs.org/) | JavaScript runtime environment | -| [npm](https://www.npmjs.com/get-npm) | Node Package Manager | -| [React](https://www.npmjs.com/package/react) | JavaScript library for UI development | -| [React DOM](https://www.npmjs.com/package/react-dom) | React package for rendering UI | - -*** - -## **Getting Started** - -### **Step 1: Create a Next.js Project** - -1. **Open your code editor** (e.g., **VS Code**, **Cursor**). -2. **Initialize a new Next.js project** using one of the following methods: + + -**Using Create Next App** ``` npx create-next-app@latest my-app --typescript @@ -109,103 +50,78 @@ cd my-app -3. **Open the project directory in your code editor**. -4. **Begin developing your Next.js application in the "app" directory.**. -5. **Install additional dependencies as needed**. + -*** + -### **Step 2: Install Dependencies** +The UI Kit package includes the CometChat JavaScript SDK as a dependency. -The **CometChat UI Kit for React** is an **extension** of the **CometChat JavaScript SDK**.\ -Installing it will **automatically** include the core **Chat SDK**, enabling **seamless integration**. - -```java +``` npm install @cometchat/chat-uikit-react ``` -*** + -### **Step 3: Initialize CometChat UI Kit** + -Before using any features of the **CometChat UI Kit** or **CometChat SDK**, you must **initialize** the required settings. +Call `CometChatUIKit.init()` at app startup before rendering any components or calling SDK methods. + + +Auth Key is for development/POC only. In production, generate Auth Tokens server-side via the REST API. See [Auth Token](/ui-kit/react/methods#login-using-auth-token). + -```ts +```ts lines highlight={4-6} import { CometChatUIKit, UIKitSettingsBuilder } from "@cometchat/chat-uikit-react"; -/** - * CometChat Constants - Replace with your actual credentials - */ const COMETCHAT_CONSTANTS = { APP_ID: "APP_ID", // Replace with your actual App ID from CometChat REGION: "REGION", // Replace with your App's Region AUTH_KEY: "AUTH_KEY", // Replace with your Auth Key (leave blank if using Auth Token) }; -/** - * Configure the CometChat UI Kit using the UIKitSettingsBuilder. - * This setup determines how the chat UI behaves. - */ const UIKitSettings = new UIKitSettingsBuilder() - .setAppId(COMETCHAT_CONSTANTS.APP_ID) // Assign the App ID - .setRegion(COMETCHAT_CONSTANTS.REGION) // Assign the App's Region - .setAuthKey(COMETCHAT_CONSTANTS.AUTH_KEY) // Assign the Authentication Key (if applicable) - .subscribePresenceForAllUsers() // Enable real-time presence updates for all users - .build(); // Build the final configuration - -/** - * Initialize the CometChat UI Kit with the configured settings. - * Once initialized successfully, you can proceed with user authentication and chat features. - */ + .setAppId(COMETCHAT_CONSTANTS.APP_ID) + .setRegion(COMETCHAT_CONSTANTS.REGION) + .setAuthKey(COMETCHAT_CONSTANTS.AUTH_KEY) + .subscribePresenceForAllUsers() + .build(); + CometChatUIKit.init(UIKitSettings)! .then(() => { console.log("CometChat UI Kit initialized successfully."); - // You can now call login function to authenticate users }) .catch((error) => { - console.error("CometChat UI Kit initialization failed:", error); // Log errors if initialization fails + console.error("CometChat UI Kit initialization failed:", error); }); ``` -```js +```js lines highlight={4-6} import { CometChatUIKit, UIKitSettingsBuilder } from "@cometchat/chat-uikit-react"; -/** - * CometChat Constants - Replace with your actual credentials - */ const COMETCHAT_CONSTANTS = { APP_ID: "APP_ID", // Replace with your actual App ID from CometChat REGION: "REGION", // Replace with your App's Region AUTH_KEY: "AUTH_KEY", // Replace with your Auth Key (leave blank if using Auth Token) }; -/** - * Configure the CometChat UI Kit using the UIKitSettingsBuilder. - * This setup determines how the chat UI behaves. - */ const UIKitSettings = new UIKitSettingsBuilder() - .setAppId(COMETCHAT_CONSTANTS.APP_ID) // Assign the App ID - .setRegion(COMETCHAT_CONSTANTS.REGION) // Assign the App's Region - .setAuthKey(COMETCHAT_CONSTANTS.AUTH_KEY) // Assign the Authentication Key (if applicable) - .subscribePresenceForAllUsers() // Enable real-time presence updates for all users - .build(); // Build the final configuration - -/** - * Initialize the CometChat UI Kit with the configured settings. - * Once initialized successfully, you can proceed with user authentication and chat features. - */ + .setAppId(COMETCHAT_CONSTANTS.APP_ID) + .setRegion(COMETCHAT_CONSTANTS.REGION) + .setAuthKey(COMETCHAT_CONSTANTS.AUTH_KEY) + .subscribePresenceForAllUsers() + .build(); + CometChatUIKit.init(UIKitSettings) .then(() => { console.log("CometChat UI Kit initialized successfully."); - // You can now call login function to authenticate users }) .catch((error) => { - console.error("CometChat UI Kit initialization failed:", error); // Log errors if initialization fails + console.error("CometChat UI Kit initialization failed:", error); }); ``` @@ -214,58 +130,34 @@ CometChatUIKit.init(UIKitSettings) - -Ensure you replace the placeholders with your actual CometChat credentials. - +Replace `APP_ID`, `AUTH_KEY`, and `REGION` with credentials from the CometChat Dashboard. -*** - -### **Step 4: User Login** - -To authenticate a user, you need a **`UID`**. You can either: - -1. **Create new users** on the **[CometChat Dashboard](https://app.cometchat.com)**, **[CometChat SDK Method](/ui-kit/react/methods#create-user)** or **[via the API](https://api-explorer.cometchat.com/reference/creates-user)**. - -2. **Use pre-generated test users**: - - * `cometchat-uid-1` - * `cometchat-uid-2` - * `cometchat-uid-3` - * `cometchat-uid-4` - * `cometchat-uid-5` - -The **Login** method returns a **User object** containing all relevant details of the logged-in user. + -*** + - - -**Security Best Practices** +Authentication requires a UID. Create users on the [CometChat Dashboard](https://app.cometchat.com), via the [SDK](/ui-kit/react/methods#create-user), or [API](https://api-explorer.cometchat.com/reference/creates-user). -* The **Auth Key** method is recommended for **proof-of-concept (POC) development** and early-stage testing. -* For **production environments**, it is strongly advised to use an **[Auth Token](/ui-kit/react/methods#login-using-auth-token)** instead of an **Auth Key** to enhance security and prevent unauthorized access. +Pre-generated test users: `cometchat-uid-1` through `cometchat-uid-5`. - +The `login` method returns a `CometChat.User` object. -```ts +```ts lines highlight={3} import { CometChatUIKit } from "@cometchat/chat-uikit-react"; const UID = "UID"; // Replace with your actual UID CometChatUIKit.getLoggedinUser().then((user: CometChat.User | null) => { if (!user) { - // If no user is logged in, proceed with login CometChatUIKit.login(UID) .then((user: CometChat.User) => { console.log("Login Successful:", { user }); - // Mount your app }) .catch(console.log); } else { - // If user is already logged in, mount your app } }); ``` @@ -273,22 +165,19 @@ CometChatUIKit.getLoggedinUser().then((user: CometChat.User | null) => { -```js +```js lines highlight={3} import { CometChatUIKit } from "@cometchat/chat-uikit-react"; const UID = "UID"; // Replace with your actual UID CometChatUIKit.getLoggedinUser().then((user) => { if (!user) { - // If no user is logged in, proceed with login CometChatUIKit.login(UID) .then((user) => { console.log("Login Successful:", { user }); - // Mount your app }) .catch(console.log); } else { - // If user is already logged in, mount your app } }); ``` @@ -297,138 +186,75 @@ CometChatUIKit.getLoggedinUser().then((user) => { -*** - -### **Step 5: Choose a Chat Experience** - -Integrate a conversation view that suits your application's **UX requirements**. Below are the available options: + -*** + -#### **1️⃣ Conversation List + Message View** +Three layout options: -**Best for:** Applications that need a **two-panel layout**, such as web-based chat interfaces (e.g., WhatsApp Web, Slack). +#### Conversation List + Message View -**Features:** - -* **Two-panel layout** – Displays the conversation list on the left and the active chat window on the right. -* **One-to-one & group conversations** – Seamless switching between private and group chats. -* **Multiple conversations** – Effortlessly switch between different chat windows. -* **Easy navigation** – Intuitive UI for finding and accessing chats quickly. -* **Tap-to-view on mobile** – In mobile layouts, tapping a conversation opens the **Message View**, optimizing space. -* **Real-time updates** – Auto-refreshes messages and conversation lists. -* **Message sync** – Ensures messages stay updated across all sessions and devices. +Two-panel layout: conversation list on the left, active chat on the right. Supports 1:1 and group conversations with real-time updates. -**Recommended for:** - -* Desktop-first applications -* Apps requiring a **rich user experience** with seamless navigation -* Platforms supporting both **individual and group messaging** -* **Mobile-friendly** apps needing a **tap-to-open message view** - [](https://link.cometchat.com/next-conversation-list-message) -> **Tip:** You can **fork** the sandbox, insert your **CometChat credentials** (App ID, Region, Auth Key.) in the code, and immediately preview how the UI and messages respond in real time. - [Integrate Conversation List + Message](./next-conversation) -*** +#### One-to-One/Group Chat -#### **2️⃣ One-to-One/Group Chat** - -**Best for:** Apps that require a **focused, direct messaging experience** without a sidebar. - -**Features:** - -* **Dedicated chat window** – Ideal for one-on-one or group messaging. -* **No conversation list** – Users directly enter the chat without navigating through a list. -* **Supports both One-to-One and Group Chats** – Easily configurable with minor code modifications. -* **Optimized for mobile** – Full-screen chat experience without distractions. -* **Seamless real-time communication** – Auto-updates messages for a smooth experience. -* **Ideal for support chat or community-based messaging.** +Single chat window without a conversation list. Supports both 1:1 and group messaging. -**Recommended for:** - -* **Support chat applications** – Direct user-agent communication. -* **Apps focusing on direct messaging** – No distractions from other conversations. -* **Community or group chat applications** – A structured way to interact in groups. -* **Mobile-first applications** – Designed for compact and dedicated messaging experiences. - [](https://link.cometchat.com/next-one-on-one) -> **Tip:** You can **fork** the sandbox, insert your **CometChat credentials** (App ID, Region, Auth Key.) in the code, and immediately preview how the UI and messages respond in real time. - [Integrate One-to-One/Group Chat](./next-one-to-one-chat) -*** - -#### **3️⃣ Tab-Based Chat Experience** - -**Best for:** Apps that need a **structured, multi-feature navigation system** for seamless interaction between **chats, calls, users, and settings**. - -**Features:** +#### Tab-Based Chat Experience -* **Tab Navigation** – Easily switch between **Chat, Call Logs, Users, and Settings**. -* **Dedicated Chat Window** – Full-screen messaging experience for focused communication. -* **No Sidebar** – Unlike multi-panel UI, this design prioritizes individual interactions. -* **Unified Experience** – Users can seamlessly manage conversations, call history, and settings from a single interface. -* **Scalable for future features** – Easily extend to include more functionalities such as notifications or contact management. -* **Optimized for both desktop and mobile** – Ensures a smooth experience across different screen sizes. +Tab navigation between Chat, Call Logs, Users, and Settings. Works across desktop and mobile. -**Recommended for:** - -* **Apps requiring structured navigation** – Clearly separate chat, calls, and settings. -* **Multi-feature chat apps** – Supporting different functionalities in an organized way. -* **Mobile-first applications** – Ideal for apps needing tab-based UI for easy access to features. -* **Support & enterprise chat solutions** – Perfect for help desks, business chat platforms, and customer support apps. - [](https://link.cometchat.com/next-tabs-sidebar-message) -> **Tip:** You can **fork** the sandbox, insert your **CometChat credentials** (App ID, Region, Auth Key.) in the code, and immediately preview how the UI and messages respond in real time. - [Integrate Tab-Based Chat](./next-tab-based-chat) -*** - -## **Build Your Own Chat Experience** - -**Best for:** Developers who need complete control over their chat interface, allowing customization of components, themes, and features to align with their app’s design and functionality. Whether you're enhancing an existing chat experience or building from scratch, this approach provides the flexibility to tailor every aspect to your needs. - -**Recommended for:** - -* Apps that require **a fully customized chat experience**. -* Developers who want to **extend functionalities and modify UI components**. -* Businesses integrating chat seamlessly into **existing platforms**. - -**Key Areas to Explore:** + + -* **[React Sample App](https://github.com/cometchat/cometchat-uikit-react/tree/v6/sample-app)** – Fully functional sample applications to accelerate your development. -* **[Core Features](./core-features)** – Learn about messaging, real-time updates, and other essential capabilities. -* **[Components](./components-overview)** – Utilize prebuilt UI elements or customize them to fit your design. -* **[Themes](./theme)** – Adjust colors, fonts, and styles to match your branding. -* **[Build Your Own UI](./../../../sdk/javascript/overview)** – Prefer a custom UI over our UI Kits? Explore our SDKs to create a tailored chat experience. +## Build Your Own Chat Experience -*** +For full control over the chat interface, use individual components directly: -## **Next Steps** +* [React Sample App](https://github.com/cometchat/cometchat-uikit-react/tree/v6/sample-app) +* [Core Features](./core-features) +* [Components](./components-overview) +* [Themes](./theme) +* [Build with SDK](./../../../sdk/javascript/overview) -Now that you’ve selected your **chat experience**, proceed to the **integration guide**: +## Next Steps -* **[Integrate Conversation List + Message](/ui-kit/react/next-conversation)** -* **[Integrate One-to-One Chat](/ui-kit/react/next-one-to-one-chat)** -* **[Integrate Tab-Based Chat](/ui-kit/react/next-tab-based-chat)** -* **[Advanced Customizations](/ui-kit/react/theme)** + + + Two-panel layout with conversation list and message view. + + + Focused direct messaging experience without a sidebar. + + + Multi-tab navigation for chats, calls, users, and settings. + + + Customize colors, fonts, and styles. + + -*** diff --git a/ui-kit/react/next-one-to-one-chat.mdx b/ui-kit/react/next-one-to-one-chat.mdx index 6b9ca33f4..d4ccb14b6 100644 --- a/ui-kit/react/next-one-to-one-chat.mdx +++ b/ui-kit/react/next-one-to-one-chat.mdx @@ -1,62 +1,57 @@ --- title: "Building A One To One/Group Chat Experience" sidebarTitle: "One To One/Group Chat" +description: "Build a focused one-to-one or group chat experience in Next.js with CometChat UI Kit." --- -The **One-to-One Chat** feature provides a streamlined **direct messaging interface**, making it ideal for **support chats, dating apps, and private messaging platforms**. This setup eliminates distractions by focusing solely on a **dedicated chat window**. + +- **Package:** `@cometchat/chat-uikit-react` +- **Framework:** Next.js +- **Key components:** `CometChatMessageHeader` + `CometChatMessageList` + `CometChatMessageComposer` +- **Required setup:** `CometChatUIKit.init(UIKitSettings)` then `CometChatUIKit.login("UID")` +- **Parent guide:** [Next.js Integration](/ui-kit/react/next-js-integration) + -[](https://link.cometchat.com/next-one-on-one) - -> **Tip:** You can **fork** the sandbox, insert your **CometChat credentials** (App ID, Region, Auth Key.) in the code, and immediately preview how the UI and messages respond in real time. +Single chat window without a conversation list. Supports both 1:1 and group messaging. -*** +[](https://link.cometchat.com/next-one-on-one) -## **User Interface Preview** +## User Interface Preview -### **Key Components** +### Key Components -1. **Chat Header** – Displays recipient details and optional call/video call buttons. -2. **Message View** – Shows real-time chat history. -3. **Message Input Box** – Enables users to send messages, media, and reactions. +1. Chat Header — recipient details and optional call/video buttons +2. Message View — real-time chat history +3. Message Composer — text input with media, emoji, and reaction support -*** +## Step-by-Step Guide -## **Step-by-Step Guide** - -### **Step 1: Implement the Chat Header** - -* Display **profile picture, name, and online status**. -* Add **voice and video call buttons** (optional). + + ```html ``` -### **Step 2: Build the Message View** - -* Load **chat history** and **real-time messages**. -* Ensure **smooth scrolling and timestamp visibility**. + + ```html ``` -### **Step 3: Add the Message Composer** - -* Include a **text input field**. -* Support **media uploads, file attachments, emojis, and reactions**. + + ```html ``` -*** - -#### **Implementation** +#### Implementation Now we will create the `CometChatNoSSR.tsx` & `CometChatNoSSR.css` files. Here, we will initialize the CometChat UI Kit, log in a user, and build the messaging experience using `CometChatMessageHeader`, `CometChatMessageList`, and `CometChatMessageComposer` components. @@ -70,7 +65,7 @@ src/ -```tsx CometChatNoSSR.tsx +```tsx CometChatNoSSR.tsx lines highlight={7-9, 31, 51, 61} import React, { useEffect, useState } from "react"; import { CometChatMessageComposer, CometChatMessageHeader, CometChatMessageList, CometChatUIKit, UIKitSettingsBuilder } from "@cometchat/chat-uikit-react"; import { CometChat } from "@cometchat/chat-sdk-javascript"; @@ -101,7 +96,7 @@ const CometChatNoSSR: React.FC = () => { console.log("Initialization completed successfully"); CometChatUIKit.getLoggedinUser().then((loggedInUser) => { if (!loggedInUser) { - CometChatUIKit.login("superhero1") + CometChatUIKit.login("cometchat-uid-2") //TODO: Replace with your actual UID .then((user) => { console.log("Login Successful", { user }); setUser(user); @@ -118,9 +113,6 @@ const CometChatNoSSR: React.FC = () => { useEffect(() => { if (user) { - // Fetch user or group from CometChat SDK whose chat you want to load. - - /** Fetching User */ const UID = "cometchat-uid-1"; CometChat.getUser(UID).then( user => { @@ -129,8 +121,6 @@ const CometChatNoSSR: React.FC = () => { console.log("User fetching failed with error:", error); } ); - - /** Fetching Group */ // const GUID = "GUID" // CometChat.getGroup(GUID).then( // group => { @@ -164,7 +154,7 @@ export default CometChatNoSSR; -```css CometChatNoSSR.css +```css CometChatNoSSR.css lines .messages-wrapper { width: 100%; height: 100%; @@ -192,12 +182,13 @@ export default CometChatNoSSR; -In the code snippet above, ensure you select either a user or a group based on your chat requirement. You can also determine this dynamically depending on the conversation type. +Select either a user or a group based on the chat requirement. -#### **Fetching a User (One-on-One Chat)** +#### Fetching a User (One-on-One Chat) -```javascript +```javascript lines highlight={1} const UID = "cometchat-uid-1"; + CometChat.getUser(UID).then( user => { setSelectedUser(user); @@ -207,10 +198,11 @@ CometChat.getUser(UID).then( ); ``` -#### **Fetching a Group (Group Chat)** +#### Fetching a Group (Group Chat) -```javascript +```javascript lines highlight={1} const GUID = "GUID" + CometChat.getGroup(GUID).then( group => { setSelectedGroup(group); @@ -220,23 +212,22 @@ CometChat.getGroup(GUID).then( ); ``` -### **Step 4: Disabling SSR for `CometChatNoSSR.tsx` in Next.js** + + In this update, we will **disable Server-Side Rendering (SSR) for `CometChatNoSSR.tsx`** while keeping the rest of the application’s SSR functionality intact. This ensures that the **CometChat UI Kit components load only on the client-side**, preventing SSR-related issues. -#### **Disabling SSR in `index.tsx`** +#### Disabling SSR in `index.tsx` Modify your `index.tsx` file to dynamically import the `CometChatNoSSR.tsx` component with `{ ssr: false }`. -```tsx index.tsx +```tsx index.tsx lines import { Inter } from "next/font/google"; import dynamic from "next/dynamic"; import '@cometchat/chat-uikit-react/css-variables.css'; const inter = Inter({ subsets: ["latin"] }); - -// Dynamically import CometChat component with SSR disabled const CometChatComponent = dynamic(() => import("../CometChatNoSSR/CometChatNoSSR"), { ssr: false, }); @@ -246,19 +237,18 @@ export default function Home() { } ``` -#### **Why disable SSR?** +#### Why disable SSR? * The CometChat UI Kit depends on browser APIs (window, document, WebSockets). * Next.js pre-renders components on the server, which can cause errors with browser-specific features. * By setting `{ ssr: false }`, we ensure that CometChatNoSSR.tsx only loads on the client. -*** - -### **Step 5: Update Global CSS** + + Next, add the following styles to global.css to ensure CometChat UI Kit is properly styled. -```css global.css +```css global.css lines :root { --background: #ffffff; --foreground: #171717; @@ -317,18 +307,47 @@ a { } ``` -*** - -### **Step 6: Run the project** + + -``` + + +```bash lines npm run dev ``` + -## **Next Steps** - -### **Enhance the User Experience** + +```bash lines +pnpm dev +``` + -* **[Advanced Customizations](/ui-kit/react/theme)** – Personalize the chat UI to align with your brand. + +```bash lines +yarn dev +``` + + -*** + + + +For prop details and customization options, see the component reference pages: [CometChatConversations](/ui-kit/react/conversations), [CometChatMessageList](/ui-kit/react/message-list), [CometChatMessageComposer](/ui-kit/react/message-composer), [CometChatMessageHeader](/ui-kit/react/message-header). + +## Next Steps + + + + Customize colors, fonts, and styles. + + + Browse all available UI components. + + + Next.js setup guide. + + + Core chat features. + + diff --git a/ui-kit/react/next-tab-based-chat.mdx b/ui-kit/react/next-tab-based-chat.mdx index 91f61a656..cc3c038dd 100644 --- a/ui-kit/react/next-tab-based-chat.mdx +++ b/ui-kit/react/next-tab-based-chat.mdx @@ -1,39 +1,39 @@ --- title: "Building A Messaging UI With Tabs, Sidebar, And Message View" sidebarTitle: "Tab Based Chat Experience" +description: "Build a tab-based messaging UI with chats, calls, users, and groups in Next.js with CometChat UI Kit." --- -This guide walks you through creating a **tab-based messaging UI** using **React** and **CometChat UIKit**. The UI will include different sections for **Chats, Calls, Users, and Groups**, allowing seamless navigation. + +- **Package:** `@cometchat/chat-uikit-react` +- **Framework:** Next.js +- **Key components:** `CometChatConversations` + `CometChatCallLogs` + `CometChatUsers` + `CometChatGroups` +- **Required setup:** `CometChatUIKit.init(UIKitSettings)` then `CometChatUIKit.login("UID")` +- **Parent guide:** [Next.js Integration](/ui-kit/react/next-js-integration) + -[](https://link.cometchat.com/next-tabs-sidebar-message) - -> **Tip:** You can **fork** the sandbox, insert your **CometChat credentials** (App ID, Region, Auth Key.) in the code, and immediately preview how the UI and messages respond in real time. +Tab-based messaging UI with sections for Chats, Calls, Users, and Groups. -*** +[](https://link.cometchat.com/next-tabs-sidebar-message) -## **User Interface Preview** +## User Interface Preview -This layout consists of: - -1. **Sidebar (Conversation List)** – Displays recent conversations with active users and groups. -2. **Message View** – Shows the selected chat with real-time messages. -3. **Message Input Box** – Allows users to send messages seamlessly. - -*** +Three sections: -## **Step-by-Step Guide** +1. Sidebar (Conversation List) — recent conversations with users and groups +2. Message View — messages for the selected chat +3. Message Composer — text input with media, emoji, and reaction support -### **Step 1: Create a Tab Component** +## Step-by-Step Guide -To manage navigation, let's build a **`CometChatTabs`** component. This component will render different tabs and allow switching between sections dynamically. + + -#### **Folder Structure** - -Create a `CometChatTabs` folder inside your `src` directory and add the following files: +Create a `CometChatTabs` folder inside `src`: ```php public/ @@ -48,43 +48,32 @@ src/ │ ├── CometChatTabs.css ``` -#### **Download the Icons** +#### Download the Icons These icons are available in the **CometChat UI Kit assets folder**. You can find them at:\ 🔗 [GitHub Assets Folder](https://github.com/cometchat/cometchat-uikit-react/tree/v6/sample-app/src/assets) -*** - -#### **Implementation** +#### Implementation -```tsx CometChatTabs.tsx +```tsx CometChatTabs.tsx lines import { useState } from "react"; import "./CometChatTabs.css"; - -// Define icon paths for each tab const chatsIcon = "/assets/chats.svg"; const callsIcon = "/assets/calls.svg"; const usersIcon = "/assets/users.svg"; const groupsIcon = "/assets/groups.svg"; - -// CometChatTabs component to display tab options export const CometChatTabs = (props: { - onTabClicked?: (tabItem: { name: string; icon?: string }) => void; // Callback when a tab is clicked - activeTab?: string; // Name of the currently active tab + onTabClicked?: (tabItem: { name: string; icon?: string }) => void; + activeTab?: string; }) => { - // Destructure props with default fallback const { - onTabClicked = () => {}, // Fallback to no-op if not provided + onTabClicked = () => {}, activeTab, } = props; - - // State to track the currently hovered tab const [hoverTab, setHoverTab] = useState(""); - - // Array of tab items with their labels and icons const tabItems = [ { name: "CHATS", icon: chatsIcon }, { name: "CALLS", icon: callsIcon }, @@ -93,9 +82,7 @@ export const CometChatTabs = (props: { ]; return ( -
- {/* Loop through each tab item to render it */} - {tabItems.map((tabItem) => { +
{tabItems.map((tabItem) => { const isActive = activeTab === tabItem.name.toLowerCase() || hoverTab === tabItem.name.toLowerCase(); @@ -104,10 +91,8 @@ export const CometChatTabs = (props: {
onTabClicked(tabItem)} // Invoke callback on click - > - {/* Icon section with mask styling */} -
onTabClicked(tabItem)} + >
setHoverTab(tabItem.name.toLowerCase())} onMouseLeave={() => setHoverTab("")} - /> - - {/* Tab label */} -
-```css CometChatTabs.css -/* Main container for the CometChat tab bar */ +```css CometChatTabs.css lines .cometchat-tab-component { - display: flex; /* Align child tabs horizontally */ - width: 100%; /* Full-width tab bar */ - padding: 0px 8px; /* Horizontal padding */ - align-items: flex-start; /* Align tab items to the top */ - gap: 8px; /* Space between tab items */ - border-top: 1px solid var(--cometchat-border-color-light, #F5F5F5); /* Top border */ - border-right: 1px solid var(--cometchat-border-color-light, #F5F5F5); /* Right border */ - background: var(--cometchat-background-color-01, #FFF); /* Background color */ + display: flex; + width: 100%; + padding: 0px 8px; + align-items: flex-start; + gap: 8px; + border-top: 1px solid var(--cometchat-border-color-light, #F5F5F5); + border-right: 1px solid var(--cometchat-border-color-light, #F5F5F5); + background: var(--cometchat-background-color-01, #FFF); } -/* Styles for each individual tab */ .cometchat-tab-component__tab { display: flex; - flex-direction: column; /* Stack icon and text vertically */ - justify-content: center; /* Center vertically */ - align-items: center; /* Center horizontally */ - padding: 12px 0px 10px 0px; /* Top and bottom spacing */ - gap: 4px; /* Space between icon and text */ - flex: 1 0 0; /* Equally distribute available space among tabs */ - min-height: 48px; /* Minimum height for consistent layout */ + flex-direction: column; + justify-content: center; + align-items: center; + padding: 12px 0px 10px 0px; + gap: 4px; + flex: 1 0 0; + min-height: 48px; } -/* Default tab icon style */ .cometchat-tab-component__tab-icon { display: flex; width: 32px; height: 32px; justify-content: center; align-items: center; - background: var(--cometchat-icon-color-secondary); /* Default icon background */ + background: var(--cometchat-icon-color-secondary); -webkit-mask-size: contain; -webkit-mask-position: center; -webkit-mask-repeat: no-repeat; @@ -187,22 +166,19 @@ export const CometChatTabs = (props: { cursor: pointer; } -/* Tab text label style */ .cometchat-tab-component__tab-text { - color: var(--cometchat-text-color-secondary, #727272); /* Default label color */ + color: var(--cometchat-text-color-secondary, #727272); text-align: center; - font: var(--cometchat-font-caption1-medium, 500 12px Roboto); /* Font style */ + font: var(--cometchat-font-caption1-medium, 500 12px Roboto); cursor: pointer; } -/* Highlighted icon style for active/hovered tab */ .cometchat-tab-component__tab-icon-active { - background: var(--cometchat-icon-color-highlight); /* Highlight color */ + background: var(--cometchat-icon-color-highlight); } -/* Highlighted text style for active/hovered tab */ .cometchat-tab-component__tab-text-active { - color: var(--cometchat-text-color-highlight); /* Highlighted text color */ + color: var(--cometchat-text-color-highlight); } ``` @@ -210,13 +186,12 @@ export const CometChatTabs = (props: { -*** - -### **Step 2: Create Sidebar** + + Let's create the `Sidebar` component which will render different conversations. -#### **Folder Structure** +#### Folder Structure Create a `CometChatSelector` folder inside your `src/app` directory and add the following files: @@ -230,7 +205,7 @@ src/ -```tsx CometChatSelector.tsx +```tsx CometChatSelector.tsx lines import { useEffect, useState } from "react"; import { Call, @@ -250,8 +225,6 @@ import { } from "@cometchat/chat-uikit-react"; import { CometChatTabs } from "../CometChatTabs/CometChatTabs"; - -// Define props interface for selector interface SelectorProps { onSelectorItemClicked?: (input: User | Group | Conversation | Call, type: string) => void; } @@ -260,25 +233,15 @@ export const CometChatSelector = (props: SelectorProps) => { const { onSelectorItemClicked = () => {}, } = props; - - // State to manage currently logged in user const [loggedInUser, setLoggedInUser] = useState(); - - // State to track selected conversation, user, group, or call const [activeItem, setActiveItem] = useState< Conversation | User | Group | Call | undefined >(); - - // State to track currently active tab: "chats", "calls", "users", or "groups" const [activeTab, setActiveTab] = useState("chats"); - - // Fetch logged-in user once component mounts useEffect(() => { const user = CometChatUIKitLoginListener.getLoggedInUser(); setLoggedInUser(user); }, [CometChatUIKitLoginListener?.getLoggedInUser()]); - - // Logout function to clear user session const logOut = () => { CometChatUIKit.logout() .then(() => { @@ -290,9 +253,7 @@ export const CometChatSelector = (props: SelectorProps) => { }; return ( - <> - {/* Render selector content only if a user is logged in */} - {loggedInUser && ( + <> {loggedInUser && ( <> {activeTab === "chats" && ( { /> )} - )} - - {/* Render the tab switcher at the bottom */} - { - setActiveTab(item.name.toLowerCase()); // Update tab on click + setActiveTab(item.name.toLowerCase()); }} /> @@ -352,66 +310,54 @@ export const CometChatSelector = (props: SelectorProps) => { -```css CometChatSelector.css -/* Style the icon inside header menu in conversation list */ +```css CometChatSelector.css lines .selector-wrapper .cometchat-conversations .cometchat-list__header-menu .cometchat-button__icon { - background: var(--cometchat-icon-color-primary); /* Primary icon color */ + background: var(--cometchat-icon-color-primary); } -/* Highlight icon on hover */ .cometchat-conversations .cometchat-list__header-menu .cometchat-button__icon:hover { - background: var(--cometchat-icon-color-highlight); /* Highlighted icon color on hover */ + background: var(--cometchat-icon-color-highlight); } -/* Remove right border from the search bar inside the list */ .cometchat-list__header-search-bar { border-right: none; } -/* Align menu list items to the left */ .cometchat .cometchat-menu-list__sub-menu-list-item { text-align: left; } -/* Positioning for the submenu inside conversations menu */ .cometchat .cometchat-conversations .cometchat-menu-list__sub-menu-list { width: 212px; top: 40px !important; left: 172px !important; } -/* Style for the logged-in user section with bottom border */ #logged-in-user { border-bottom: 2px solid var(--cometchat-border-color-default, #E8E8E8); } -/* Make submenu items under logged-in user non-clickable */ #logged-in-user .cometchat-menu-list__sub-menu-item-title, #logged-in-user .cometchat-menu-list__sub-menu-list-item { cursor: default; } -/* Logout icon color inside submenu */ .cometchat-menu-list__sub-menu-list-item-icon-log-out { - background-color: var(--cometchat-error-color, #F44649); /* Error color */ + background-color: var(--cometchat-error-color, #F44649); } -/* Logout label/text color inside submenu */ .cometchat-menu-list__sub-menu-item-title-log-out { color: var(--cometchat-error-color, #F44649); } -/* Enable pointer cursor for chat menu item titles */ .chat-menu .cometchat .cometchat-menu-list__sub-menu-item-title { cursor: pointer; } -/* Remove shadow from the chat menu's submenu */ .chat-menu .cometchat .cometchat-menu-list__sub-menu { box-shadow: none; } -/* Style the icons inside chat menu items */ .chat-menu .cometchat .cometchat-menu-list__sub-menu-icon { background-color: var(--cometchat-icon-color-primary, #141414); width: 24px; @@ -423,14 +369,15 @@ export const CometChatSelector = (props: SelectorProps) => { -### **Step 3: Render Experience** + + Now we will update the `CometChatNoSSR.tsx` & `CometChatNoSSR.css` files to import these new components as below, -```tsx CometChatNoSSR.tsx +```tsx CometChatNoSSR.tsx lines highlight={15-17, 45} import React, { useEffect, useState } from "react"; import { CometChatMessageComposer, @@ -442,40 +389,29 @@ import { import { CometChat } from "@cometchat/chat-sdk-javascript"; import { CometChatSelector } from "../CometChatSelector/CometChatSelector"; import "./CometChatNoSSR.css"; - -// Constants for CometChat configuration const COMETCHAT_CONSTANTS = { APP_ID: "", REGION: "", AUTH_KEY: "", }; - -// Functional component for CometChatNoSSR const CometChatNoSSR: React.FC = () => { - // State to store the logged-in user const [user, setUser] = useState(undefined); - // State to store selected user or group const [selectedUser, setSelectedUser] = useState(undefined); const [selectedGroup, setSelectedGroup] = useState(undefined); useEffect(() => { - // Initialize UIKit settings const UIKitSettings = new UIKitSettingsBuilder() .setAppId(COMETCHAT_CONSTANTS.APP_ID) .setRegion(COMETCHAT_CONSTANTS.REGION) .setAuthKey(COMETCHAT_CONSTANTS.AUTH_KEY) .subscribePresenceForAllUsers() .build(); - - // Initialize CometChat UIKit CometChatUIKit.init(UIKitSettings) ?.then(() => { console.log("Initialization completed successfully"); - // Check if user is already logged in CometChatUIKit.getLoggedinUser().then((loggedInUser) => { if (!loggedInUser) { - // Perform login if no user is logged in - CometChatUIKit.login("cometchat-uid-4") + CometChatUIKit.login("cometchat-uid-4") //TODO: Replace with dynamic UID as needed .then((user) => { console.log("Login Successful", { user }); setUser(user); @@ -491,17 +427,13 @@ const CometChatNoSSR: React.FC = () => { }, []); return user ? ( -
- {/* Sidebar with conversation list */} -
+
{ let item = activeItem; - // Extract the conversation participant if (activeItem instanceof CometChat.Conversation) { item = activeItem.getConversationWith(); } - // Update states based on the type of selected item if (item instanceof CometChat.User) { setSelectedUser(item as CometChat.User); setSelectedGroup(undefined); @@ -514,10 +446,7 @@ const CometChatNoSSR: React.FC = () => { } }} /> -
- - {/* Message view section */} - {selectedUser || selectedGroup ? ( +
{selectedUser || selectedGroup ? (
@@ -537,38 +466,33 @@ export default CometChatNoSSR; -```css CometChatNoSSR.css -/* Layout for the main container that holds conversations and messages */ +```css CometChatNoSSR.css lines .conversations-with-messages { display: flex; height: 100%; width: 100%; } -/* Sidebar wrapper for conversation list */ .conversations-wrapper { height: 100%; - width: 480px; /* Fixed width for conversation list */ - overflow: hidden; /* Hide any overflowing content */ + width: 480px; + overflow: hidden; display: flex; flex-direction: column; height: inherit; } -/* Hide overflow content inside the conversation component */ .conversations-wrapper > .cometchat { overflow: hidden; } -/* Message section layout */ .messages-wrapper { - width: calc(100% - 480px); /* Take remaining space */ + width: calc(100% - 480px); height: 100%; display: flex; flex-direction: column; } -/* Styling for when no conversation is selected */ .empty-conversation { height: 100%; width: 100%; @@ -580,7 +504,6 @@ export default CometChatNoSSR; font: var(--cometchat-font-body-regular, 400 14px Roboto); } -/* Ensure message composer does not have rounded corners */ .cometchat .cometchat-message-composer { border-radius: 0px; } @@ -590,23 +513,22 @@ export default CometChatNoSSR; -### **Step 4: Disabling SSR for `CometChatNoSSR.tsx` in Next.js** + + In this update, we will **disable Server-Side Rendering (SSR) for `CometChatNoSSR.tsx`** while keeping the rest of the application’s SSR functionality intact. This ensures that the **CometChat UI Kit components load only on the client-side**, preventing SSR-related issues. -#### **Disabling SSR in `index.tsx`** +#### Disabling SSR in `index.tsx` Modify your `index.tsx` file to dynamically import the `CometChatNoSSR.tsx` component with `{ ssr: false }`. -```tsx index.tsx +```tsx index.tsx lines import { Inter } from "next/font/google"; import dynamic from "next/dynamic"; import '@cometchat/chat-uikit-react/css-variables.css'; const inter = Inter({ subsets: ["latin"] }); - -// Dynamically import CometChat component with SSR disabled const CometChatComponent = dynamic(() => import("../CometChatNoSSR/CometChatNoSSR"), { ssr: false, }); @@ -616,17 +538,18 @@ export default function Home() { } ``` -#### **Why disable SSR?** +#### Why disable SSR? * The CometChat UI Kit depends on browser APIs (window, document, WebSockets). * Next.js pre-renders components on the server, which can cause errors with browser-specific features. * By setting `{ ssr: false }`, we ensure that CometChatNoSSR.tsx only loads on the client. -### **Step 5: Update Global CSS** + + Next, add the following styles to global.css to ensure CometChat UI Kit is properly styled. -```css global.css +```css global.css lines :root { --background: #ffffff; --foreground: #171717; @@ -685,18 +608,47 @@ a { } ``` -### **Step 6: Run the project** + + -``` + + +```bash lines npm run dev ``` + -*** - -## **Next Steps** - -### **Enhance the User Experience** + +```bash lines +pnpm dev +``` + -* **[Advanced Customizations](/ui-kit/react/theme)** – Personalize the chat UI to align with your brand. + +```bash lines +yarn dev +``` + + -*** + + + +For prop details and customization options, see the component reference pages: [CometChatConversations](/ui-kit/react/conversations), [CometChatMessageList](/ui-kit/react/message-list), [CometChatMessageComposer](/ui-kit/react/message-composer), [CometChatMessageHeader](/ui-kit/react/message-header). + +## Next Steps + + + + Customize colors, fonts, and styles. + + + Browse all available UI components. + + + Next.js setup guide. + + + Core chat features. + + diff --git a/ui-kit/react/outgoing-call.mdx b/ui-kit/react/outgoing-call.mdx index 89413847a..ca83af719 100644 --- a/ui-kit/react/outgoing-call.mdx +++ b/ui-kit/react/outgoing-call.mdx @@ -1,1028 +1,721 @@ --- title: "Outgoing Call" +description: "Overlay component displaying an outgoing voice/video call with recipient info and cancel control." --- + +```json +{ + "component": "CometChatOutgoingCall", + "package": "@cometchat/chat-uikit-react", + "import": "import { CometChatOutgoingCall } from \"@cometchat/chat-uikit-react\";", + "cssImport": "import \"@cometchat/chat-uikit-react/css-variables.css\";", + "description": "Overlay component displaying an outgoing voice/video call with recipient info and cancel control.", + "cssRootClass": ".cometchat-outgoing-call", + "primaryOutput": { + "prop": "onCallCanceled", + "type": "Function" + }, + "props": { + "data": { + "call": { + "type": "CometChat.Call", + "default": "undefined", + "note": "Must come from CometChat.initiateCall()" + } + }, + "callbacks": { + "onCallCanceled": "Function", + "onError": "((error: CometChat.CometChatException) => void) | null" + }, + "sound": { + "disableSoundForCalls": { "type": "boolean", "default": false }, + "customSoundForCalls": { "type": "string", "default": "built-in" } + }, + "viewSlots": { + "titleView": "JSX.Element", + "subtitleView": "JSX.Element", + "avatarView": "JSX.Element", + "cancelButtonView": "JSX.Element" + } + }, + "events": [ + { + "name": "CometChatCallEvents.ccOutgoingCall", + "payload": "CometChat.Call", + "description": "Call initiated" + }, + { + "name": "CometChatCallEvents.ccCallAccepted", + "payload": "CometChat.Call", + "description": "Recipient accepts" + }, + { + "name": "CometChatCallEvents.ccCallRejected", + "payload": "CometChat.Call", + "description": "Recipient rejects" + }, + { + "name": "CometChatCallEvents.ccCallEnded", + "payload": "CometChat.Call", + "description": "Call session ends" + } + ], + "sdkListeners": [], + "compositionExample": { + "description": "App-level overlay rendered after CometChat.initiateCall()", + "components": ["CometChatOutgoingCall"], + "flow": "CometChat.initiateCall() returns CometChat.Call -> pass to call prop -> onCallCanceled ends session" + } +} +``` + -## Overview - -The outgoing call component is a visual representation of a user-initiated call, whether it's a voice or video call. It serves as an interface for managing outgoing calls, providing users with essential options to control the call experience. This component typically includes information about the call recipient, call controls for canceling the call, and feedback on the call status, such as indicating when the call is in progress. - - - - - -The `Outgoing Call` is comprised of the following components: - -| Components | Description | -| ---------------- | ------------------------------------------------------------------------------------------------------------------- | -| CometChat Button | This component represents a button with optional icon and text. | -| CometChat Avatar | This component component displays an image or user's avatar with fallback to the first two letters of the username. | - -## Usage +## Where It Fits -### Integration +`CometChatOutgoingCall` is an overlay component that displays the outgoing call screen with the recipient's name, avatar, and a cancel button. It plays a ringtone while the call is pending. Typically rendered at the app root level after initiating a call via `CometChat.initiateCall()`. - - ```tsx +import { useState, useEffect } from "react"; import { CometChat } from "@cometchat/chat-sdk-javascript"; import { CometChatOutgoingCall, CometChatUIKitConstants, } from "@cometchat/chat-uikit-react"; -import React from "react"; +import "@cometchat/chat-uikit-react/css-variables.css"; -const OutgoingCallDemo = () => { - const [call, setCall] = React.useState(); +function OutgoingCallDemo() { + const [call, setCall] = useState(); - React.useEffect(() => { + useEffect(() => { const uid = "uid"; - const callObject = new CometChat.Call( uid, CometChatUIKitConstants.MessageTypes.audio, CometChatUIKitConstants.MessageReceiverType.user ); CometChat.initiateCall(callObject) - .then((c) => { - setCall(c); - }) + .then((c) => setCall(c)) .catch(console.log); }, []); return call ? : null; -}; +} export default OutgoingCallDemo; ``` - + + + + +--- + +## Minimal Render - ```tsx -import { OutgoingCallDemo } from "./OutgoingCallDemo"; +import { CometChatOutgoingCall } from "@cometchat/chat-uikit-react"; +import "@cometchat/chat-uikit-react/css-variables.css"; -export default function App() { - return ( -
-
- -
-
- ); +function OutgoingCallMinimal() { + // `call` must be a CometChat.Call object from CometChat.initiateCall() + return call ? : null; } ``` -
+Root CSS class: `.cometchat-outgoing-call` -
+--- -### Actions +## Actions and Events -[Actions](/ui-kit/react/components-overview#actions) dictate how a component functions. They are divided into two types: Predefined and User-defined. You can override either type, allowing you to tailor the behavior of the component to fit your specific needs. +### Callback Props -##### 1. onCallCanceled +#### onCallCanceled -The `onCallCanceled` event gets activated when the cancel button is clicked. It does not have a default behavior. However, you can override its behavior using the following code snippet. +Fires when the cancel button is clicked. Pauses the ringtone internally before invoking the callback. - - -```ts +```tsx +import { useState, useEffect } from "react"; import { CometChat } from "@cometchat/chat-sdk-javascript"; import { CometChatOutgoingCall, CometChatUIKitConstants, } from "@cometchat/chat-uikit-react"; -import React from "react"; -const OutgoingCallDemo = () => { - const [call, setCall] = React.useState(); +function OutgoingCallWithCancel() { + const [call, setCall] = useState(); - React.useEffect(() => { + useEffect(() => { const uid = "uid"; - const callObject = new CometChat.Call( uid, CometChatUIKitConstants.MessageTypes.audio, CometChatUIKitConstants.MessageReceiverType.user ); CometChat.initiateCall(callObject) - .then((c) => { - setCall(c); - }) + .then((c) => setCall(c)) .catch(console.log); }, []); const cancelCall = () => { - //your custom cancel call click actions - CometChat.endCall(call!.getSessionId()).then(() => { - setCall(undefined); - }); + CometChat.endCall(call!.getSessionId()).then(() => setCall(undefined)); }; + return call ? ( ) : null; -}; +} +``` -export default OutgoingCallDemo; +#### onError + +Fires on internal errors. + +```tsx +import { CometChatOutgoingCall } from "@cometchat/chat-uikit-react"; +import { CometChat } from "@cometchat/chat-sdk-javascript"; + +function OutgoingCallWithError() { + return ( + { + console.error("OutgoingCall error:", error); + }} + /> + ); +} ``` - +### Global UI Events - -```js -import React, { useState, useEffect } from 'react'; -import { CometChat } from '@cometchat/chat-sdk-javascript'; -import { CometChatOutgoingCall, CometChatUIKitConstants } from '@cometchat/chat-uikit-react'; +`CometChatCallEvents` emits call lifecycle events subscribable from anywhere. Subscribe in a `useEffect` and unsubscribe on cleanup. -const OutgoingCallDemo = () => { - const [call, setCall] = useState(null); +| Event | Fires when | Payload | +| --- | --- | --- | +| `ccOutgoingCall` | A call is initiated | `CometChat.Call` | +| `ccCallAccepted` | The recipient accepts the call | `CometChat.Call` | +| `ccCallRejected` | The recipient rejects the call | `CometChat.Call` | +| `ccCallEnded` | The call session ends | `CometChat.Call` | - useEffect(() => { - const uid = "uid"; +```tsx +import { useEffect } from "react"; +import { CometChatCallEvents } from "@cometchat/chat-uikit-react"; +import { CometChat } from "@cometchat/chat-sdk-javascript"; - const callObject = new CometChat.Call( - uid, - CometChatUIKitConstants.MessageTypes.audio, - CometChatUIKitConstants.MessageReceiverType.user +function useCallEvents() { + useEffect(() => { + const acceptedSub = CometChatCallEvents.ccCallAccepted.subscribe( + (call: CometChat.Call) => { + console.log("Call accepted:", call.getSessionId()); + } + ); + const rejectedSub = CometChatCallEvents.ccCallRejected.subscribe( + (call: CometChat.Call) => { + console.log("Call rejected:", call.getSessionId()); + } + ); + const endedSub = CometChatCallEvents.ccCallEnded.subscribe( + (call: CometChat.Call) => { + console.log("Call ended:", call.getSessionId()); + } ); - CometChat.initiateCall(callObject) - .then((c) => { - setCall(c); - }) - .catch(console.log); + return () => { + acceptedSub?.unsubscribe(); + rejectedSub?.unsubscribe(); + endedSub?.unsubscribe(); + }; }, []); +} +``` - const cancelCall = () =>{ - //your custom cancel call click actions - CometChat.endCall(call!.getSessionId()) - .then(() => { - setCall(undefined); - }) - }; +### SDK Events (Real-Time, Automatic) - return ( - call && ( - - ) - ); -}; -export default OutgoingCallDemo; -``` +The component internally manages call sound playback. It plays the outgoing call ringtone on mount (unless `disableSoundForCalls={true}`) and pauses it on unmount or cancel. No SDK call listeners are attached by the component itself — call status updates are handled by the parent application. - +--- - +## Custom View Slots + +All view slots on `CometChatOutgoingCall` are `JSX.Element` (not functions). They do not receive parameters — pass call data via closure if needed. -##### 2. onError +| Slot | Type | Replaces | +| --- | --- | --- | +| `titleView` | `JSX.Element` | Recipient name | +| `subtitleView` | `JSX.Element` | "Calling..." text | +| `avatarView` | `JSX.Element` | Recipient avatar | +| `cancelButtonView` | `JSX.Element` | Cancel call button | -This action doesn't change the behavior of the component but rather listens for any errors that occur in the Outgoing Call component. +### titleView + +Replace the recipient name. + + + + -```ts +```tsx import { CometChat } from "@cometchat/chat-sdk-javascript"; import { CometChatOutgoingCall, CometChatUIKitConstants, } from "@cometchat/chat-uikit-react"; -import React from "react"; - -const OutgoingCallDemo = () => { - const [call, setCall] = React.useState(); - - React.useEffect(() => { - const uid = "uid"; - - const callObject = new CometChat.Call( - uid, - CometChatUIKitConstants.MessageTypes.audio, - CometChatUIKitConstants.MessageReceiverType.user - ); - CometChat.initiateCall(callObject) - .then((c) => { - setCall(c); - }) - .catch(console.log); - }, []); - function handleOnError(error: CometChat.CometChatException) { - //Your Custom Error Actions - console.log(error); - } +function OutgoingCallCustomTitle() { + // assume `call` is a CometChat.Call from CometChat.initiateCall() + const getTitleView = (call: CometChat.Call) => ( +
+ {call.getCallInitiator().getName()} {" <> "}{" "} + {call.getCallReceiver().getName()} +
+ ); return call ? ( - + ) : null; -}; - -export default OutgoingCallDemo; +} ``` -
- - -```js -import React, { useState, useEffect } from "react"; -import { CometChat } from "@cometchat/chat-sdk-javascript"; -import { - CometChatOutgoingCall, - CometChatUIKitConstants, -} from "@cometchat/chat-uikit-react"; - -const OutgoingCallDemo = () => { - const [call, setCall] = useState(null); - - useEffect(() => { - const uid = "uid"; - - const callObject = new CometChat.Call( - uid, - CometChatUIKitConstants.MessageTypes.audio, - CometChatUIKitConstants.MessageReceiverType.user - ); - - CometChat.initiateCall(callObject) - .then((c) => { - setCall(c); - }) - .catch(console.log); - }, []); - - function handleOnError(error) { - //Your Custom Error Actions - console.log(error); - } - return call && ; -}; - -export default OutgoingCallDemo; + +```css +.outgoing-call__title { + color: #141414; + text-align: center; + font: 500 24px Roboto; +} ``` - -
-*** - -### Filters - -**Filters** allow you to customize the data displayed in a list within a `Component`. You can filter the list based on your specific criteria, allowing for a more customized. Filters can be applied using `RequestBuilders` of Chat SDK. - -The `Outgoing Call` component does not have any exposed filters. - -*** - -### Events - -[Events](/ui-kit/react/components-overview#events) are emitted by a `Component`. By using event you can extend existing functionality. Being global events, they can be applied in Multiple Locations and are capable of being Added or Removed. - -The `Outgoing Call` component does not have any exposed filters. +### subtitleView -*** +Replace the "Calling..." text. -## Customization + + + -To fit your app's design requirements, you can customize the appearance of the Outgoing Call component. We provide exposed methods that allow you to modify the experience and behavior according to your specific needs. + + +```tsx +const getSubtitleView = (call: CometChat.Call) => ( +
+
+ {"Calling..."} +
+); + +; +``` + + +```css +.outgoing-call__subtitle { + display: flex; + justify-content: center; + align-items: flex-start; + gap: 8px; + color: #727272; + text-align: center; + font: 400 16px Roboto; +} -### Style +.outgoing-call__subtitle-icon { + -webkit-mask: url("") center center no-repeat; + background: #a1a1a1; + height: 24px; + width: 24px; +} +``` + + -Using CSS you can customize the look and feel of the component in your app like the color, size, shape, and fonts. +### avatarView -**Example** +Replace the recipient avatar. - + -```ts -import { CometChat } from "@cometchat/chat-sdk-javascript"; +```tsx import { + CometChatAvatar, CometChatOutgoingCall, - CometChatUIKitConstants, - OutgoingCallStyle, } from "@cometchat/chat-uikit-react"; -import React from "react"; - -const OutgoingCallDemo = () => { - const [call, setCall] = React.useState(); - - React.useEffect(() => { - const uid = "uid"; - - const callObject = new CometChat.Call( - uid, - CometChatUIKitConstants.MessageTypes.audio, - CometChatUIKitConstants.MessageReceiverType.user - ); - CometChat.initiateCall(callObject) - .then((c) => { - setCall(c); - }) - .catch(console.log); - }, []); +import { CometChat } from "@cometchat/chat-sdk-javascript"; - return call ? : null; -}; +function OutgoingCallCustomAvatar() { + const getAvatarView = (call: CometChat.Call) => ( +
+ +
+
+ ); -export default OutgoingCallDemo; + return call ? ( + + ) : null; +} ``` - + +```css +.outgoing-call__avatar .cometchat-avatar, +.outgoing-call__avatar .cometchat-avatar__image { + width: 160px; + height: 160px; + border-radius: 20px; +} - -```js -import React, { useState, useEffect } from "react"; -import { CometChat } from "@cometchat/chat-sdk-javascript"; -import { - CometChatOutgoingCall, - CometChatUIKitConstants, - OutgoingCallStyle, -} from "@cometchat/chat-uikit-react"; - -const OutgoingCallDemo = () => { - const [call, setCall] = useState(null); +.outgoing-call__avatar-status { + background-image: url(""); + height: 44px; + width: 44px; + background-size: contain; + position: relative; + top: -45px; + right: -60px; +} +``` + + - useEffect(() => { - const uid = "uid"; +### cancelButtonView - const callObject = new CometChat.Call( - uid, - CometChatUIKitConstants.MessageTypes.audio, - CometChatUIKitConstants.MessageReceiverType.user - ); +Replace the cancel call button. - CometChat.initiateCall(callObject) - .then((c) => { - setCall(c); - }) - .catch(console.log); - }, []); + + + - return call && ; -}; + + +```tsx +function OutgoingCallCustomCancel() { + const getCancelButtonView = (call: CometChat.Call) => ( +
+
+
+ {"End Call"} +
+
+ ); -export default OutgoingCallDemo; + return call ? ( + + ) : null; +} ``` - - - + ```css -.cometchat-outgoing-call__avatar .cometchat-avatar { +.outgoing-call__cancel-button-wrapper { + height: 64px; display: flex; justify-content: center; - align-items: center; - flex-shrink: 0; - border-radius: 16px; - background: #fbaa75; + cursor: pointer; } -.cometchat-outgoing-call__button { +.outgoing-call__cancel-button { display: flex; + width: 330px; + padding: 12px 30px; + justify-content: center; align-items: center; - border-radius: 8px; - background: #f44649; + gap: 12px; + border-radius: 12px; + background-color: #f44649; + color: #fff; + font: 500 20px Roboto; } -.cometchat-outgoing-call .cometchat-outgoing-call__title { - text-align: center; - font: 400 32px/38px "Times New Roman"; +.outgoing-call__cancel-button-icon { + -webkit-mask: url("") center center no-repeat; + background: #e8e8e8; + height: 32px; + width: 32px; } ``` - - -### Functionality +--- -These are a set of small functional customizations that allow you to fine-tune the overall experience of the component. With these, you can change text, set custom icons, and toggle the visibility of UI elements. +## Common Patterns -Here is a code snippet demonstrating how you can customize the functionality of the `Outgoing Call` component. +### Cancel and end the call session - - -```ts +```tsx +import { useState, useEffect } from "react"; import { CometChat } from "@cometchat/chat-sdk-javascript"; import { CometChatOutgoingCall, CometChatUIKitConstants, } from "@cometchat/chat-uikit-react"; -import React from "react"; -const OutgoingCallDemo = () => { - const [call, setCall] = React.useState(); +function OutgoingCallWithEndSession() { + const [call, setCall] = useState(); - React.useEffect(() => { + useEffect(() => { const uid = "uid"; - const callObject = new CometChat.Call( uid, CometChatUIKitConstants.MessageTypes.audio, CometChatUIKitConstants.MessageReceiverType.user ); CometChat.initiateCall(callObject) - .then((c) => { - setCall(c); - }) + .then((c) => setCall(c)) .catch(console.log); }, []); + const handleCancel = () => { + if (call) { + CometChat.endCall(call.getSessionId()).then(() => setCall(undefined)); + } + }; + return call ? ( - + ) : null; -}; - -export default OutgoingCallDemo; +} ``` - - - -```js -import React, { useState, useEffect } from "react"; -import { CometChat } from "@cometchat/chat-sdk-javascript"; -import { - CometChatOutgoingCall, - CometChatUIKitConstants, -} from "@cometchat/chat-uikit-react"; +### Custom ringtone -const OutgoingCallDemo = () => { - const [call, setCall] = useState(null); - - useEffect(() => { - const uid = "uid"; - - const callObject = new CometChat.Call( - uid, - CometChatUIKitConstants.MessageTypes.audio, - CometChatUIKitConstants.MessageReceiverType.user - ); - - CometChat.initiateCall(callObject) - .then((c) => { - setCall(c); - }) - .catch(console.log); - }, []); +```tsx +import { CometChatOutgoingCall } from "@cometchat/chat-uikit-react"; +function OutgoingCallCustomSound() { return ( - call && + ); -}; - -export default OutgoingCallDemo; -``` - - - - - -Below is a list of customizations along with corresponding code snippets - -| Property | Description | Code | -| ----------------- | ---------------------------------------------------------------------- | --------------------------------------------------- | -| **Call** | The CometChat call object used to set up and launch the outgoing call. | `call={call}` | -| **Disable Sound** | Disables the sound of outgoing calls. | `disableSoundForCalls={false}` | -| **Custom Sound** | Specifies a custom sound to play for outgoing calls. | `customSoundForCalls='Your Custom Sound For Calls'` | - -*** - -### Advanced - -For advanced-level customization, you can set custom views to the component. This lets you tailor each aspect of the component to fit your exact needs and application aesthetics. You can create and define your views, layouts, and UI elements and then incorporate those into the component. - -*** - -#### TitleView - -This prop renders the custom title view for the outgoing call. Use this to override the existing title of user name from the outgoing call. - -The customized chat interface is displayed below. - - - - - -Use the following code to achieve the customization shown above. - - - -```ts -import { CometChat } from "@cometchat/chat-sdk-javascript"; -import { - CometChatOutgoingCall, - CometChatUIKitConstants, -} from "@cometchat/chat-uikit-react"; -import React from "react"; - -const OutgoingCallDemo = () => { - const [call, setCall] = React.useState(); - - React.useEffect(() => { - const uid = "uid"; - - const callObject = new CometChat.Call( - uid, - CometChatUIKitConstants.MessageTypes.audio, - CometChatUIKitConstants.MessageReceiverType.user - ); - CometChat.initiateCall(callObject) - .then((c) => { - setCall(c); - }) - .catch(console.log); - }, []); - - const getTitleView = (call: Call) => { - return ( -
- {call.getCallInitiator().getName()} {" <> "} {call.getCallReceiver().getName()} -
- ); - }; - - return ( - call && - ); -}; - -export default OutgoingCallDemo; +} ``` -
- - -```js -import React, { useState, useEffect } from "react"; -import { CometChat } from "@cometchat/chat-sdk-javascript"; -import { - CometChatOutgoingCall, - CometChatUIKitConstants, -} from "@cometchat/chat-uikit-react"; - -const OutgoingCallDemo = () => { - const [call, setCall] = useState(null); - - useEffect(() => { - const uid = "uid"; - - const callObject = new CometChat.Call( - uid, - CometChatUIKitConstants.MessageTypes.audio, - CometChatUIKitConstants.MessageReceiverType.user - ); +### Silent outgoing call (no ringtone) - CometChat.initiateCall(callObject) - .then((c) => { - setCall(c); - }) - .catch(console.log); - }, []); - - const getTitleView = (call) => { - return ( -
- {call.getCallInitiator().getName()} {" <> "} {call.getCallReceiver().getName()} -
- ); - }; +```tsx +import { CometChatOutgoingCall } from "@cometchat/chat-uikit-react"; +function SilentOutgoingCall() { return ( - call && + ); -}; - -export default OutgoingCallDemo; +} ``` -
+--- - -```css -.outgoing-call__title { - color: #141414; - text-align: center; - font: 500 24px Roboto; -} -``` +## CSS Architecture - +The component uses CSS custom properties (design tokens) defined in `@cometchat/chat-uikit-react/css-variables.css`. The cascade: -
+1. Global tokens (e.g., `--cometchat-primary-color`, `--cometchat-error-color`) set on the `.cometchat` root wrapper. +2. Component CSS (`.cometchat-outgoing-call`) consumes these tokens via `var()` with fallback values. +3. Overrides target `.cometchat-outgoing-call` descendant selectors in a global stylesheet. -#### SubtitleView +### Key Selectors -This prop renders the custom sub title view for the outgoing call. Use this to override the existing sub title text from the outgoing call. +| Target | Selector | +| --- | --- | +| Root | `.cometchat-outgoing-call` | +| Title container | `.cometchat-outgoing-call__title-container` | +| Title text | `.cometchat-outgoing-call__title` | +| Subtitle text | `.cometchat-outgoing-call__subtitle` | +| Avatar container | `.cometchat-outgoing-call__avatar` | +| Avatar image | `.cometchat-outgoing-call__avatar .cometchat-avatar` | +| Avatar text | `.cometchat-outgoing-call__avatar .cometchat-avatar__text` | +| Cancel button wrapper | `.cometchat-outgoing-call__button` | +| Cancel button | `.cometchat-outgoing-call__button .cometchat-button` | +| Cancel button icon | `.cometchat-outgoing-call__button .cometchat-button .cometchat-button__icon` | -The customized chat interface is displayed below. +### Example: Themed outgoing call - + -Use the following code to achieve the customization shown above. - - - -```ts -import { CometChat } from "@cometchat/chat-sdk-javascript"; -import { - CometChatOutgoingCall, - CometChatUIKitConstants, -} from "@cometchat/chat-uikit-react"; -import React from "react"; - -const OutgoingCallDemo = () => { - const [call, setCall] = React.useState(); - - React.useEffect(() => { - const uid = "uid"; - - const callObject = new CometChat.Call( - uid, - CometChatUIKitConstants.MessageTypes.audio, - CometChatUIKitConstants.MessageReceiverType.user - ); - CometChat.initiateCall(callObject) - .then((c) => { - setCall(c); - }) - .catch(console.log); - }, []); - - const getSubtitleView = (call: Call) => { - return ( -
-
- {"Calling..."} -
- ); - }; - - return ( - call && - ); -}; - -export default OutgoingCallDemo; -``` - - - - -```js -import React, { useState, useEffect } from "react"; -import { CometChat } from "@cometchat/chat-sdk-javascript"; -import { - CometChatOutgoingCall, - CometChatUIKitConstants, -} from "@cometchat/chat-uikit-react"; - -const OutgoingCallDemo = () => { - const [call, setCall] = useState(null); - - useEffect(() => { - const uid = "uid"; - - const callObject = new CometChat.Call( - uid, - CometChatUIKitConstants.MessageTypes.audio, - CometChatUIKitConstants.MessageReceiverType.user - ); - - CometChat.initiateCall(callObject) - .then((c) => { - setCall(c); - }) - .catch(console.log); - }, []); - - const getSubtitleView = (call) => { - return ( -
-
- {"Calling..."} -
- ); - }; - - return ( - call && - ); -}; - -export default OutgoingCallDemo; -``` - - - - ```css -.outgoing-call__subtitle { - display: flex; - justify-content: center; - align-items: flex-start; - gap: 8px; - color: #727272; - text-align: center; - font: 400 16px Roboto; +.cometchat-outgoing-call__avatar .cometchat-avatar { + border-radius: 16px; + background: #fbaa75; } -.outgoing-call__subtitle-icon { - -webkit-mask: url("") center center no-repeat; - background: #A1A1A1; - height: 24px; - width: 24px; +.cometchat-outgoing-call__button .cometchat-button { + border-radius: 8px; + background: #f44649; +} + +.cometchat-outgoing-call .cometchat-outgoing-call__title { + text-align: center; + font: 400 32px/38px "Times New Roman"; } ``` - +### Customization Matrix - +| What to change | Where | Property/API | Example | +| --- | --- | --- | --- | +| Handle cancel action | Component props | `onCallCanceled` | `onCallCanceled={() => endCall()}` | +| Disable ringtone | Component props | `disableSoundForCalls` | `disableSoundForCalls={true}` | +| Custom ringtone | Component props | `customSoundForCalls` | `customSoundForCalls="/sounds/ring.mp3"` | +| Replace UI sections | Component props | View slot props | `titleView={
Custom
}` | +| Change colors, fonts, spacing | Global CSS | Target `.cometchat-outgoing-call` class | `.cometchat-outgoing-call__title { color: red; }` | -#### AvatarView +--- -This prop renders the custom avatar view for the outgoing call. Use this to override the existing avatar image from the outgoing call. +## Accessibility -The customized chat interface is displayed below. +The component renders a modal-like overlay. The cancel button is keyboard-focusable and activates on Enter/Space. The recipient name and "Calling..." subtitle are rendered as text content accessible to screen readers. The avatar includes the recipient name as alt text via `CometChatAvatar`. - - - +--- -Use the following code to achieve the customization shown above. +--- - - -```ts -import { CometChat } from "@cometchat/chat-sdk-javascript"; -import { - CometChatAvatar, - CometChatOutgoingCall, - CometChatUIKitConstants, -} from "@cometchat/chat-uikit-react"; -import React from "react"; +## Props -const OutgoingCallDemo = () => { - const [call, setCall] = React.useState(); +All props are optional unless noted. Sorted alphabetically. - React.useEffect(() => { - const uid = "uid"; +### avatarView - const callObject = new CometChat.Call( - uid, - CometChatUIKitConstants.MessageTypes.audio, - CometChatUIKitConstants.MessageReceiverType.user - ); - CometChat.initiateCall(callObject) - .then((c) => { - setCall(c); - }) - .catch(console.log); - }, []); - - const getAvatarView = (call: CometChat.Call) => { - return ( -
- -
-
- ); - }; - - return ( - call && - ); -}; +Custom JSX replacing the recipient avatar. -export default OutgoingCallDemo; -``` +| | | +| --- | --- | +| Type | `JSX.Element` | +| Default | Built-in avatar | - +--- - -```js -import React, { useState, useEffect } from "react"; -import { CometChat } from "@cometchat/chat-sdk-javascript"; -import { - CometChatAvatar, - CometChatOutgoingCall, - CometChatUIKitConstants, -} from "@cometchat/chat-uikit-react"; +### call -const OutgoingCallDemo = () => { - const [call, setCall] = useState(null); +The outgoing call object from `CometChat.initiateCall()`. - useEffect(() => { - const uid = "uid"; +| | | +| --- | --- | +| Type | `CometChat.Call` | +| Default | `undefined` | - const callObject = new CometChat.Call( - uid, - CometChatUIKitConstants.MessageTypes.audio, - CometChatUIKitConstants.MessageReceiverType.user - ); +Component renders nothing when `call` is not provided. - CometChat.initiateCall(callObject) - .then((c) => { - setCall(c); - }) - .catch(console.log); - }, []); +--- - const getAvatarView = (call) => { - return ( -
- -
-
- ); - }; +### cancelButtonView - return ( - call && - ); -}; +Custom JSX replacing the cancel call button. -export default OutgoingCallDemo; -``` +| | | +| --- | --- | +| Type | `JSX.Element` | +| Default | Built-in cancel button | - - - -```css -.outgoing-call__avatar .cometchat-avatar, -.outgoing-call__avatar .cometchat-avatar__image { - width: 160px; - height: 160px; - border-radius: 20px; -} - -.outgoing-call__avatar-status { - background-image: url(""); - height: 44px; - width: 44px; - background-size: contain; - position: relative; - top: -45px; - right: -60px; -} -``` +--- - +### customSoundForCalls - +URL to a custom audio file for the outgoing call ringtone. -#### CancelButtonView +| | | +| --- | --- | +| Type | `string` | +| Default | Built-in ringtone | -This prop renders the custom cancel-call button view for the outgoing call. Use this to override the existing cancel call button view from the outgoing call. +--- -The customized chat interface is displayed below. +### disableSoundForCalls - - - +Disables the outgoing call ringtone. -Use the following code to achieve the customization shown above. +| | | +| --- | --- | +| Type | `boolean` | +| Default | `false` | - - -```ts -import { CometChat } from "@cometchat/chat-sdk-javascript"; -import { - CometChatOutgoingCall, - CometChatUIKitConstants, -} from "@cometchat/chat-uikit-react"; -import React from "react"; +--- -const OutgoingCallDemo = () => { - const [call, setCall] = React.useState(); +### onCallCanceled - React.useEffect(() => { - const uid = "uid"; +Callback fired when the cancel button is clicked. - const callObject = new CometChat.Call( - uid, - CometChatUIKitConstants.MessageTypes.audio, - CometChatUIKitConstants.MessageReceiverType.user - ); - CometChat.initiateCall(callObject) - .then((c) => { - setCall(c); - }) - .catch(console.log); - }, []); +| | | +| --- | --- | +| Type | `Function` | +| Default | `undefined` | - const getCancelButtonView = (call: Call) => { - return ( -
-
-
- {"End Call"} -
-
- ); - }; +--- - return ( - call && - ); -}; +### onError -export default OutgoingCallDemo; -``` +Callback fired when the component encounters an error. - +| | | +| --- | --- | +| Type | `((error: CometChat.CometChatException) => void) \| null` | +| Default | `undefined` | - -```js -import React, { useState, useEffect } from "react"; -import { CometChat } from "@cometchat/chat-sdk-javascript"; -import { - CometChatOutgoingCall, - CometChatUIKitConstants, -} from "@cometchat/chat-uikit-react"; +--- -const OutgoingCallDemo = () => { - const [call, setCall] = useState(null); +### subtitleView - useEffect(() => { - const uid = "uid"; +Custom JSX replacing the "Calling..." subtitle text. - const callObject = new CometChat.Call( - uid, - CometChatUIKitConstants.MessageTypes.audio, - CometChatUIKitConstants.MessageReceiverType.user - ); +| | | +| --- | --- | +| Type | `JSX.Element` | +| Default | Built-in subtitle | - CometChat.initiateCall(callObject) - .then((c) => { - setCall(c); - }) - .catch(console.log); - }, []); +--- - const getCancelButtonView = (call) => { - return ( -
-
-
- {"End Call"} -
-
- ); - }; +### titleView - return ( - call && - ); -}; +Custom JSX replacing the recipient name. -export default OutgoingCallDemo; -``` +| | | +| --- | --- | +| Type | `JSX.Element` | +| Default | Built-in title | - +--- - -```css -.outgoing-call__cancel-button-wrapper { - height: 64px; - display: flex; - justify-content: center; - cursor: pointer; -} +## Events -.outgoing-call__cancel-button { - display: flex; - width: 330px; - padding: 12px 30px; - justify-content: center; - align-items: center; - gap: 12px; - align-self: stretch; - border-radius: 12px; - background-color: #F44649; - color: #FFF; - font: 500 20px Roboto; -} +| Event | Payload | Fires when | +| --- | --- | --- | +| `CometChatCallEvents.ccOutgoingCall` | `CometChat.Call` | Call initiated | +| `CometChatCallEvents.ccCallAccepted` | `CometChat.Call` | Recipient accepts | +| `CometChatCallEvents.ccCallRejected` | `CometChat.Call` | Recipient rejects | +| `CometChatCallEvents.ccCallEnded` | `CometChat.Call` | Call session ends | -.outgoing-call__cancel-button-icon { - -webkit-mask: url("") center center no-repeat; - background: #E8E8E8; - height: 32px; - width: 32px; -} -``` +All events are `Subject` from RxJS. Subscribe with `.subscribe()`, unsubscribe with the returned subscription's `.unsubscribe()`. - +--- - +## CSS Selectors + +| Target | Selector | +| --- | --- | +| Root | `.cometchat-outgoing-call` | +| Title container | `.cometchat-outgoing-call__title-container` | +| Title text | `.cometchat-outgoing-call__title` | +| Subtitle text | `.cometchat-outgoing-call__subtitle` | +| Avatar container | `.cometchat-outgoing-call__avatar` | +| Avatar image | `.cometchat-outgoing-call__avatar .cometchat-avatar` | +| Avatar text | `.cometchat-outgoing-call__avatar .cometchat-avatar__text` | +| Cancel button wrapper | `.cometchat-outgoing-call__button` | +| Cancel button | `.cometchat-outgoing-call__button .cometchat-button` | +| Cancel button icon | `.cometchat-outgoing-call__button .cometchat-button .cometchat-button__icon` | diff --git a/ui-kit/react/overview.mdx b/ui-kit/react/overview.mdx index 42b82d980..3df158836 100644 --- a/ui-kit/react/overview.mdx +++ b/ui-kit/react/overview.mdx @@ -1,22 +1,24 @@ --- title: "CometChat UI Kit For React" sidebarTitle: "Overview" +description: "Prebuilt, customizable React UI components for adding chat, voice, and video calling to your app. Supports React.js, Next.js, React Router, and Astro." --- -The **CometChat UI Kit** for React is a powerful solution designed to seamlessly integrate chat functionality into applications. It provides a robust set of **prebuilt UI components** that are **modular, customizable, and highly scalable**, allowing developers to accelerate their development process with minimal effort. + +- **Package:** `@cometchat/chat-uikit-react` +- **Install:** `npm install @cometchat/chat-uikit-react` +- **Required setup:** `CometChatUIKit.init(UIKitSettings)` then `CometChatUIKit.login("UID")` — must complete before rendering any component +- **Key components:** `CometChatConversations`, `CometChatMessageList`, `CometChatMessageComposer`, `CometChatMessageHeader`, `CometChatUsers`, `CometChatGroups` +- **Theming:** Override CSS variables on `.cometchat` class. See [Theming](/ui-kit/react/theme) +- **Calling:** Requires separate `@cometchat/calls-sdk-javascript` package. See [Call Features](/ui-kit/react/call-features) +- **SSR:** Components require browser APIs — use client-side only rendering for Next.js/Astro + -*** - -## **Why Choose CometChat UI Kit?** - -* **Rapid Integration** – Prebuilt UI components for faster deployment. -* **Customizable & Flexible** – Modify the UI to align with your brand’s identity. -* **Cross-Platform Compatibility** – Works seamlessly across various React-based frameworks. -* **Scalable & Reliable** – Built on CometChat's **robust chat infrastructure** for enterprise-grade performance. +The CometChat UI Kit for React provides prebuilt, modular UI components for in-app chat, voice, and video calling. Components are customizable via CSS variables and support light/dark theming. *** -## **User Interface Preview** +## User Interface Preview @@ -24,9 +26,7 @@ The **CometChat UI Kit** for React is a powerful solution designed to seamlessly *** -## **Try Live Demo** - -**Experience the CometChat UI Kit in action:** +## Try Live Demo @@ -43,85 +43,16 @@ href="https://link.cometchat.com/react-conversation-list-message" - -{/* [](https://link.cometchat.com/cometchat-demo) - -[](https://link.cometchat.com/react-conversation-list-message) */} - - -> **Tip:** You can **fork** the sandbox, insert your **CometChat credentials** (App ID, Region, Auth Key) in the code, and immediately preview how the UI and messages respond in real time. - -*** - -## **Integration** - -{/* ### **Option 1: UI Kit Builder (Pre-Assembled UI)** - -A ready-to-use chat interface—configured via a UI Kit Builder—built on top of our UI Kits. - - - - - -**How It Works** - -* Toggle features like @mentions, reactions, media uploads, and more in a visual interface. -* Drag-and-drop or point-and-click to enable or disable components. -* Customize layouts and styles—no deep coding required. - -**Why It’s Great** - -* **Fastest Setup** – Minimal component wiring. -* **Continuous Customization** – Only turn on the features you want. -* **Fewer Moving Parts** – Reliable, pre-assembled UI that’s easy to maintain. - - - -} - href="/ui-kit/react/builder-integration" - horizontal -/> - -} - href="/ui-kit/react/builder-integration-nextjs" - horizontal -/> - -} - href="/ui-kit/react/builder-integration-react-router" - horizontal -/> - - - *** -### **Option 2: UI Components (Assemble It Yourself)** */} +## Integration -A collection of individual components—like conversation lists, message lists, message composer, etc.—each with built-in chat logic so you can customize every element. +Individual components — conversation lists, message lists, message composer, etc. — each with built-in chat logic. Import, arrange in a layout, and apply styling as needed. -**How It Works** - -* Import the components you need from our UI Kits. -* Arrange them in your desired layout, applying styling or customization as needed. -* You don’t need to rewrite the SDK calls yourself—each component already integrates with CometChat logic. - -**Why It’s Great** - -* **Flexible Design** – You control the final UI arrangement. -* **No Extra Overhead** – Implement only the features you need. -* **Modular** – Use exactly what you want, when you want. - -*** - -## **Next Steps for Developers** - -1. **Learn the Basics** – [Key Concepts](/fundamentals/key-concepts). - -2. **Pick a Framework** – React.js or Next.js or React Router or Astro. - -3. **Follow the Setup Guide** – - - * **UI Components** – [React.js](/ui-kit/react/react-js-integration) or [Next.js](/ui-kit/react/next-js-integration) or [React Router](/ui-kit/react/react-router-integration) or [Astro](/ui-kit/react/astro-integration). - -4. **Customize UI** – Adjust [styles, themes](/ui-kit/react/theme), and [components](/ui-kit/react/components-overview). +*** -5. **Test & Deploy** – Run tests and launch your chat app. - -*** - -## **Helpful Resources** - -Explore these essential resources to gain a deeper understanding of **CometChat UI Kits** and streamline your integration process. +## Helpful Resources - - Fully functional sample applications to accelerate your development. - - View on GitHub - + Fully functional sample application. - - Access the complete UI Kit source code on GitHub. - - View on GitHub - + Complete UI Kit source on GitHub. - UI design resources for customization and prototyping. - - View on Figma - *** -## **Need Help?** - -If you need assistance, check out: +## Need Help? -* [Developer Community](http://community.cometchat.com/) * [Support Portal](https://help.cometchat.com/hc/en-us/requests/new) + +--- + +## Next Steps + + + + Step-by-step setup for React.js applications + + + Browse all available prebuilt UI components + + + Chat features included out of the box + + + Customize colors, fonts, and styles + + diff --git a/ui-kit/react/property-changes.mdx b/ui-kit/react/property-changes.mdx index 3358b3d16..d9dca0b7f 100644 --- a/ui-kit/react/property-changes.mdx +++ b/ui-kit/react/property-changes.mdx @@ -1,6 +1,14 @@ --- title: "Property Changes" +description: "Detailed reference of renamed, added, and removed properties and methods when upgrading from CometChat React UI Kit v5 to v6." --- + +- **Migration scope:** Property and method changes between v5 and v6 for all components +- **Components affected:** Conversations, Users, Groups, Group Members, Message Header, Message List, Message Composer, Incoming Call, Outgoing Call, Call Buttons, Call Logs, CometChatLocalize +- **Key pattern change:** `datePattern` (DatePatterns) replaced with `CalendarObject`-based props across all components +- **Localization:** `setLocale` → `setCurrentLanguage`, `localize` → `getLocalizedString` +- **Full migration guide:** [Upgrading from v5](/ui-kit/react/upgrading-from-v5) + ## Conversations @@ -92,3 +100,20 @@ title: "Property Changes" | setDefaultLanguage | Sets the default lannguage if no language is passed in init method. | | isRTL | Returns true if the active language is rtl otherwise return false. | | getDir | Returns `rtl` or `ltr` based on the active language. | + +## Next Steps + + + + Full migration guide with breaking changes. + + + Explore all v6 prebuilt UI components. + + + Init, login, logout, and other UI Kit methods. + + + Subscribe to real-time events across components. + + diff --git a/ui-kit/react/react-conversation.mdx b/ui-kit/react/react-conversation.mdx index 03ab256f4..b4e74e238 100644 --- a/ui-kit/react/react-conversation.mdx +++ b/ui-kit/react/react-conversation.mdx @@ -1,41 +1,39 @@ --- title: "Building A Conversation List + Message View" sidebarTitle: "Conversation List + Message View" +description: "Build a two-panel conversation list + message view layout in React.js with CometChat UI Kit." --- -The **Conversation List + Message View** layout offers a seamless **two-panel chat interface**, commonly used in modern messaging applications like **WhatsApp Web, Slack, and Microsoft Teams**. + +- **Package:** `@cometchat/chat-uikit-react` +- **Framework:** React.js +- **Key components:** `CometChatConversations` + `CometChatMessageList` +- **Required setup:** `CometChatUIKit.init(UIKitSettings)` then `CometChatUIKit.login("UID")` +- **Parent guide:** [React.js Integration](/ui-kit/react/react-js-integration) + -This design enables users to switch between conversations effortlessly while keeping the chat window open, ensuring a **smooth, real-time messaging experience**. +Two-panel chat layout: conversation list on the left, active chat on the right. Supports 1:1 and group conversations with real-time updates. [](https://link.cometchat.com/react-conversation-list-message) -> **Tip:** You can **fork** the sandbox, insert your **CometChat credentials** (App ID, Region, Auth Key.) in the code, and immediately preview how the UI and messages respond in real time. - -*** - -## **User Interface Overview** +## User Interface Overview -This layout is structured into three key sections: - -1. **Sidebar (Conversation List)** – Displays active conversations, including users and groups. -2. **Message View** – Shows chat messages for the selected conversation in real-time. -3. **Message Composer** – Provides an input field for typing and sending messages, along with support for media, emojis, and reactions. - -*** +Three sections: -## **Step-by-Step Guide** +1. Sidebar (Conversation List) — active conversations (users and groups) +2. Message View — messages for the selected conversation +3. Message Composer — text input with media, emoji, and reaction support -### **Step 1: Create Sidebar** +## Step-by-Step Guide -Let's create the `Sidebar` component which will render different conversations. + + -#### **Folder Structure** - -Create a `CometChatSelector` folder inside your `src` directory and add the following files: +Create a `CometChatSelector` folder inside `src`: ``` src/ @@ -47,7 +45,7 @@ src/ -```tsx CometChatSelector.tsx +```tsx CometChatSelector.tsx lines import { useEffect, useState } from "react"; import { Conversation, @@ -60,8 +58,6 @@ import { CometChatUIKitLoginListener, } from "@cometchat/chat-uikit-react"; import "./CometChatSelector.css"; - -// Define the props for the CometChatSelector component interface SelectorProps { onSelectorItemClicked?: ( input: User | Group | Conversation, @@ -70,29 +66,19 @@ interface SelectorProps { onHide?: () => void; onNewChatClicked?: () => void; } - -// CometChatSelector component export const CometChatSelector = (props: SelectorProps) => { - // Destructure props with a default function for onSelectorItemClicked const { onSelectorItemClicked = () => {} } = props; - - // State to store the logged-in user const [loggedInUser, setLoggedInUser] = useState(); - - // State to track the currently selected item (it can be a Conversation, User, or Group) const [activeItem, setActiveItem] = useState< CometChat.Conversation | CometChat.User | CometChat.Group | undefined >(); - - // useEffect hook to fetch and set the logged-in user useEffect(() => { const loggedInUser = CometChatUIKitLoginListener.getLoggedInUser(); setLoggedInUser(loggedInUser); - }, [loggedInUser]); // Dependency on loggedInUser causes unnecessary re-renders + }, [loggedInUser]); return ( <> - {/* Render chat conversations if a user is logged in */} {loggedInUser && ( <> { : undefined } onItemClick={(e) => { - setActiveItem(e); // Update the active item when an item is clicked - onSelectorItemClicked(e, "updateSelectedItem"); // Notify parent component + setActiveItem(e); + onSelectorItemClicked(e, "updateSelectedItem"); }} /> @@ -118,73 +104,60 @@ export const CometChatSelector = (props: SelectorProps) => { -```css CometChatSelector.css -/* Styles for the menu icon in the conversation header */ +```css CometChatSelector.css lines .selector-wrapper .cometchat-conversations .cometchat-list__header-menu .cometchat-button__icon { background: var(--cometchat-icon-color-primary); } -/* Change background color of the menu icon on hover */ .cometchat-conversations .cometchat-list__header-menu .cometchat-button__icon:hover { background: var(--cometchat-icon-color-highlight); } -/* Remove the right border from the search bar */ .cometchat-list__header-search-bar { border-right: none; } -/* Aligns submenu list items to the left */ .cometchat .cometchat-menu-list__sub-menu-list-item { text-align: left; } -/* Adjust the width and positioning of the conversation menu list */ .cometchat .cometchat-conversations .cometchat-menu-list__sub-menu-list { width: 212px; top: 40px !important; left: 172px !important; } -/* Styles for the logged-in user section */ #logged-in-user { border-bottom: 2px solid var(--cometchat-border-color-default, #E8E8E8); } -/* Disable cursor interaction for menu items inside logged-in user section */ #logged-in-user .cometchat-menu-list__sub-menu-item-title, #logged-in-user .cometchat-menu-list__sub-menu-list-item { cursor: default; } -/* Background color for the logout button icon */ .cometchat-menu-list__sub-menu-list-item-icon-log-out { background-color: var(--cometchat-error-color, #F44649); } -/* Text color for the logout menu item */ .cometchat-menu-list__sub-menu-item-title-log-out { color: var(--cometchat-error-color, #F44649); } -/* Enable pointer cursor for menu items inside the chat menu */ .chat-menu .cometchat .cometchat-menu-list__sub-menu-item-title { cursor: pointer; } -/* Remove box-shadow from submenu in the chat menu */ .chat-menu .cometchat .cometchat-menu-list__sub-menu { box-shadow: none; } -/* Styles for the submenu icon inside the chat menu */ .chat-menu .cometchat .cometchat-menu-list__sub-menu-icon { background-color: var(--cometchat-icon-color-primary, #141414); width: 24px; height: 24px; } -/* Styling for the chat selector container */ .cometchat-selector { display: flex; width: 100%; @@ -196,7 +169,6 @@ export const CometChatSelector = (props: SelectorProps) => { background: var(--cometchat-background-color-01, #FFF); } -/* Styling for each tab inside the chat selector */ .cometchat-selector__tab { display: flex; padding: 12px 0px 10px 0px; @@ -208,7 +180,6 @@ export const CometChatSelector = (props: SelectorProps) => { min-height: 48px; } -/* Styles for the active tab icon */ .cometchat-selector__tab-icon-active { display: flex; width: 32px; @@ -223,7 +194,6 @@ export const CometChatSelector = (props: SelectorProps) => { mask: url('./assets/chats.svg') no-repeat center; } -/* Styles for the active tab text */ .cometchat-selector__tab-text-active { text-align: center; font: var(--cometchat-font-caption1-medium, 500 12px Roboto); @@ -236,14 +206,15 @@ export const CometChatSelector = (props: SelectorProps) => { -### **Step 2: Update App** + + -Now we will update the `App.tsx` & `App.css` files to import these new components as below, +Update `App.tsx` and `App.css`: -```tsx App.tsx +```tsx App.tsx lines import { useState } from "react"; import { CometChatMessageComposer, @@ -256,54 +227,38 @@ import "./App.css"; import '@cometchat/chat-uikit-react/css-variables.css'; function App() { - // State to track the currently selected user const [selectedUser, setSelectedUser] = useState(undefined); - - // State to track the currently selected group const [selectedGroup, setSelectedGroup] = useState(undefined); return (
- {/* Sidebar for selecting conversations */}
{ let item = activeItem; - - // If the selected item is a conversation, extract the user/group from it if (activeItem instanceof CometChat.Conversation) { item = activeItem.getConversationWith(); } - - // Determine if the selected item is a User or a Group and update the state accordingly if (item instanceof CometChat.User) { setSelectedUser(item as CometChat.User); - setSelectedGroup(undefined); // Ensure no group is selected + setSelectedGroup(undefined); } else if (item instanceof CometChat.Group) { - setSelectedUser(undefined); // Ensure no user is selected + setSelectedUser(undefined); setSelectedGroup(item as CometChat.Group); } else { setSelectedUser(undefined); - setSelectedGroup(undefined); // Reset if selection is invalid + setSelectedGroup(undefined); } }} />
- - {/* If a user or group is selected, display the chat interface */} {selectedUser || selectedGroup ? (
- {/* Header displaying user/group details */} - - {/* List of messages for the selected user/group */} - - {/* Message input composer */}
) : ( - // Default message when no conversation is selected
Select Conversation to start
)}
@@ -317,38 +272,33 @@ export default App; -```css App.css -/* Root container settings */ +```css App.css lines #root { text-align: center; - width: 100vw; /* Full viewport width */ - height: 100vh; /* Full viewport height */ - background-color: #282c34; /* Dark background */ + width: 100vw; + height: 100vh; + background-color: #282c34; } -/* Layout container for conversations and messages */ .conversations-with-messages { display: flex; height: 100%; width: 100%; - flex-direction: row; /* Horizontal layout */ + flex-direction: row; } -/* Sidebar container for the conversation list */ .conversations-wrapper { height: 100vh; - width: 480px; /* Fixed width for the sidebar */ + width: 480px; overflow: hidden; display: flex; flex-direction: column; } -/* Prevent scrolling inside the conversation list */ .conversations-wrapper > .cometchat { overflow: hidden; } -/* Main chat messages container */ .messages-wrapper { width: 100%; height: 100%; @@ -356,19 +306,17 @@ export default App; flex-direction: column; } -/* Styles for the placeholder when no conversation is selected */ .empty-conversation { height: 100vh; width: 100%; display: flex; justify-content: center; align-items: center; - background: var(--cometchat-background-color-03, #F5F5F5); /* Light gray background */ - color: var(--cometchat-text-color-secondary, #727272); /* Secondary text color */ + background: var(--cometchat-background-color-03, #F5F5F5); + color: var(--cometchat-text-color-secondary, #727272); font: var(--cometchat-font-body-regular, 400 14px Roboto); } -/* Remove border-radius for the message composer input */ .cometchat .cometchat-message-composer { border-radius: 0px; } @@ -378,18 +326,41 @@ export default App;
-### **Step 3: Run the project** +
+ -```powershell -npm start + + +```bash lines +npm run dev ``` + -*** - -## **Next Steps** - -### **Enhance the User Experience** - -* **[Advanced Customizations](/ui-kit/react/theme)** – Personalize the chat UI to align with your brand. + +```bash lines +npm start +``` + + -*** + +
+ +For prop details and customization options, see the component reference pages: [CometChatConversations](/ui-kit/react/conversations), [CometChatMessageList](/ui-kit/react/message-list), [CometChatMessageComposer](/ui-kit/react/message-composer), [CometChatMessageHeader](/ui-kit/react/message-header). + +## Next Steps + + + + Customize colors, fonts, and styles. + + + Browse all available UI components. + + + React.js setup guide. + + + Core chat features. + + diff --git a/ui-kit/react/react-js-integration.mdx b/ui-kit/react/react-js-integration.mdx index 55d433935..54f7c1dba 100644 --- a/ui-kit/react/react-js-integration.mdx +++ b/ui-kit/react/react-js-integration.mdx @@ -1,104 +1,40 @@ --- title: "Getting Started With CometChat React UI Kit" sidebarTitle: "Integration" +description: "Step-by-step guide to integrate CometChat React UI Kit into your React.js application with Vite or Create React App." --- -The **CometChat UI Kit for React** streamlines the integration of in-app chat functionality by providing a **comprehensive set of prebuilt UI components**. It offers seamless **theming options**, including **light and dark modes**, customizable fonts, colors, and extensive styling capabilities. + +- **Package:** `@cometchat/chat-uikit-react` — `npm install @cometchat/chat-uikit-react` +- **Required setup:** `CometChatUIKit.init(UIKitSettings)` then `CometChatUIKit.login("UID")` — must complete before rendering +- **Init code:** `new UIKitSettingsBuilder().setAppId("APP_ID").setRegion("REGION").setAuthKey("AUTH_KEY").build()` +- **Framework:** React.js (this page) | [Next.js](/ui-kit/react/next-js-integration) | [React Router](/ui-kit/react/react-router-integration) | [Astro](/ui-kit/react/astro-integration) +- **All components:** [Components Overview](/ui-kit/react/components-overview) + -With built-in support for **one-to-one and group conversations**, developers can efficiently enable chat features within their applications. Follow this guide to **quickly integrate chat functionality** using the CometChat React UI Kit. - -{/* - - */} +The CometChat UI Kit for React provides prebuilt UI components for in-app chat — one-to-one and group conversations, theming (light/dark modes), and calling. This guide covers project setup, initialization, login, and rendering a first component. -*** - -## **Prerequisites** - -Before installing the **CometChat UI Kit for React**, you must first **create a CometChat application** via the **[CometChat Dashboard](https://app.cometchat.com/)**. The dashboard provides all the essential chat service components, including: - -* **User Management** -* **Group Chat & Messaging** -* **Voice & Video Calling** -* **Real-time Notifications** - -> To initialize the **UI Kit**, you will need the following credentials from your **CometChat application**: -> -> 1. **App ID** -> 2. **Auth Key** -> 3. **Region** -> -> Ensure you have these details ready before proceeding with the installation and configuration. - -*** - -## **Register & Set Up CometChat** - -Follow these steps to **register on CometChat** and **set up your development environment**. - -### **Step 1: Register on CometChat** - -To use **CometChat UI Kit**, you first need to register on the **CometChat Dashboard**. - -🔗 **[Click here to Sign Up](https://app.cometchat.com/login)** - -### **Step 2: Get Your Application Keys** - -After registering, create a **new app** and retrieve your **authentication details**: - -1. Navigate to **Application**, then select the **Credentials** section. - -2. Note down the following keys: - - * **App ID** - * **Auth Key** - * **Region** - - - -Each CometChat application can be integrated with a **single client app**. Users within the same application can communicate across multiple platforms, including **web and mobile**. - - - -### **Step 3: Set Up Your Development Environment** - -Ensure your system meets the following **prerequisites** before proceeding with integration. - -**System Requirements:** - -* **Node.js** installed on your machine. -* A code editor like **[Visual Studio Code](https://code.visualstudio.com/)** or **[Cursor](https://www.cursor.com/)**. -* **npm** or **Yarn** package manager installed. +## Prerequisites -*** +Create a CometChat application via the [CometChat Dashboard](https://app.cometchat.com/). The dashboard provides user management, group chat, voice/video calling, and real-time notifications. -## **Built With** +Required credentials from the dashboard: -The CometChat UI Kit for React relies on the following technologies: +1. App ID +2. Auth Key +3. Region -| Technology | Description | -| ---------------------------------------------------- | ------------------------------------- | -| [Node.js](https://nodejs.org/) | JavaScript runtime environment | -| [npm](https://www.npmjs.com/get-npm) | Node Package Manager | -| [React](https://www.npmjs.com/package/react) | JavaScript library for UI development | -| [React DOM](https://www.npmjs.com/package/react-dom) | React package for rendering UI | +## Getting Started -*** - -## **Getting Started** - -### **Step 1: Create a React Project** - -1. **Open your code editor** (e.g., **VS Code**, **Cursor**). -2. **Initialize a new React project** using one of the following methods: + + -**Using Vite (Recommended)** ``` npm create vite@latest my-app --template react-ts @@ -108,7 +44,6 @@ cd my-app -**Using Create React App** ``` npx create-react-app my-app --template typescript @@ -119,18 +54,11 @@ cd my-app -3. **Open the project directory in your code editor**. -4. **Start developing your React components inside the src directory**. -5. **Install additional dependencies as needed**. - -*** - -### **Step 2: Install Dependencies** + -The **CometChat UI Kit for React** is an **extension** of the **CometChat JavaScript SDK**.\ -Installing it will **automatically** include the core **Chat SDK**, enabling **seamless integration**. + -* To install the **CometChat UI Kit** +The UI Kit package includes the CometChat JavaScript SDK as a dependency. @@ -149,103 +77,68 @@ yarn add @cometchat/chat-uikit-react -*** + -### **Step 3: Initialize CometChat UI Kit** + -Before using any features of the **CometChat UI Kit** or **CometChat SDK**, you must **initialize** the required settings. This is done using the [`Init`](/ui-kit/react/methods#init) method. - -* Initialization Process - -Call the `Init` method at the **beginning of your application** to ensure all CometChat functionalities are properly configured. - -*** +Call `CometChatUIKit.init()` at app startup before rendering any components or calling SDK methods. -**Auth Key Usage** - -The **Auth Key** is an **optional property** of the `UIKitSettings` class. It is primarily recommended for **proof-of-concept (POC) development** or **early-stage application development**. - -For secure authentication, use the [`Auth Token`](/ui-kit/react/methods#login-using-auth-token) method instead. - +Auth Key is for development/POC only. In production, generate Auth Tokens server-side via the REST API. See [Auth Token](/ui-kit/react/methods#login-using-auth-token). -```ts +```ts lines highlight={4-6} import { CometChatUIKit, UIKitSettingsBuilder } from "@cometchat/chat-uikit-react"; -/** - * CometChat Constants - Replace with your actual credentials - */ const COMETCHAT_CONSTANTS = { APP_ID: "APP_ID", // Replace with your actual App ID from CometChat REGION: "REGION", // Replace with your App's Region AUTH_KEY: "AUTH_KEY", // Replace with your Auth Key (leave blank if using Auth Token) }; -/** - * Configure the CometChat UI Kit using the UIKitSettingsBuilder. - * This setup determines how the chat UI behaves. - */ const UIKitSettings = new UIKitSettingsBuilder() - .setAppId(COMETCHAT_CONSTANTS.APP_ID) // Assign the App ID - .setRegion(COMETCHAT_CONSTANTS.REGION) // Assign the App's Region - .setAuthKey(COMETCHAT_CONSTANTS.AUTH_KEY) // Assign the Authentication Key (if applicable) - .subscribePresenceForAllUsers() // Enable real-time presence updates for all users - .build(); // Build the final configuration - -/** - * Initialize the CometChat UI Kit with the configured settings. - * Once initialized successfully, you can proceed with user authentication and chat features. - */ + .setAppId(COMETCHAT_CONSTANTS.APP_ID) + .setRegion(COMETCHAT_CONSTANTS.REGION) + .setAuthKey(COMETCHAT_CONSTANTS.AUTH_KEY) + .subscribePresenceForAllUsers() + .build(); + CometChatUIKit.init(UIKitSettings)! .then(() => { console.log("CometChat UI Kit initialized successfully."); - // You can now call login function to authenticate users }) .catch((error) => { - console.error("CometChat UI Kit initialization failed:", error); // Log errors if initialization fails + console.error("CometChat UI Kit initialization failed:", error); }); ``` -```js +```js lines highlight={4-6} import { CometChatUIKit, UIKitSettingsBuilder } from "@cometchat/chat-uikit-react"; -/** - * CometChat Constants - Replace with your actual credentials - */ const COMETCHAT_CONSTANTS = { APP_ID: "APP_ID", // Replace with your actual App ID from CometChat REGION: "REGION", // Replace with your App's Region AUTH_KEY: "AUTH_KEY", // Replace with your Auth Key (leave blank if using Auth Token) }; -/** - * Configure the CometChat UI Kit using the UIKitSettingsBuilder. - * This setup determines how the chat UI behaves. - */ const UIKitSettings = new UIKitSettingsBuilder() - .setAppId(COMETCHAT_CONSTANTS.APP_ID) // Assign the App ID - .setRegion(COMETCHAT_CONSTANTS.REGION) // Assign the App's Region - .setAuthKey(COMETCHAT_CONSTANTS.AUTH_KEY) // Assign the Authentication Key (if applicable) - .subscribePresenceForAllUsers() // Enable real-time presence updates for all users - .build(); // Build the final configuration - -/** - * Initialize the CometChat UI Kit with the configured settings. - * Once initialized successfully, you can proceed with user authentication and chat features. - */ + .setAppId(COMETCHAT_CONSTANTS.APP_ID) + .setRegion(COMETCHAT_CONSTANTS.REGION) + .setAuthKey(COMETCHAT_CONSTANTS.AUTH_KEY) + .subscribePresenceForAllUsers() + .build(); + CometChatUIKit.init(UIKitSettings) .then(() => { console.log("CometChat UI Kit initialized successfully."); - // You can now call login function to authenticate users }) .catch((error) => { - console.error("CometChat UI Kit initialization failed:", error); // Log errors if initialization fails + console.error("CometChat UI Kit initialization failed:", error); }); ``` @@ -254,70 +147,38 @@ CometChatUIKit.init(UIKitSettings) - -Ensure you replace the following placeholders with your actual CometChat credentials: - -* APP\_ID → Your CometChat App ID -* AUTH\_KEY → Your CometChat Auth Key -* REGION → Your App Region - -These values are required for proper authentication and seamless integration. - +Replace `APP_ID`, `AUTH_KEY`, and `REGION` with credentials from the CometChat Dashboard. - -You can choose between different storage methods to store data. By default, we use local storage. To learn more about available storage options and how to configure them, [click here](/ui-kit/react/methods#setting-session-storage-mode). - +By default, the UI Kit uses local storage. See [storage options](/ui-kit/react/methods#setting-session-storage-mode) for alternatives. -*** - -### **Step 4: User Login** - -To authenticate a user, you need a **`UID`**. You can either: - -1. **Create new users** on the **[CometChat Dashboard](https://app.cometchat.com)**, **[CometChat SDK Method](/ui-kit/react/methods#create-user)** or **[via the API](https://api-explorer.cometchat.com/reference/creates-user)**. - -2. **Use pre-generated test users**: - - * `cometchat-uid-1` - * `cometchat-uid-2` - * `cometchat-uid-3` - * `cometchat-uid-4` - * `cometchat-uid-5` - -The **Login** method returns a **User object** containing all relevant details of the logged-in user. + -*** + - - -**Security Best Practices** +Authentication requires a UID. Create users on the [CometChat Dashboard](https://app.cometchat.com), via the [SDK](/ui-kit/react/methods#create-user), or [API](https://api-explorer.cometchat.com/reference/creates-user). -* The **Auth Key** method is recommended for **proof-of-concept (POC) development** and early-stage testing. -* For **production environments**, it is strongly advised to use an **[Auth Token](/ui-kit/react/methods#login-using-auth-token)** instead of an **Auth Key** to enhance security and prevent unauthorized access. +Pre-generated test users: `cometchat-uid-1` through `cometchat-uid-5`. - +The `login` method returns a `CometChat.User` object. -```ts +```ts lines highlight={3} import { CometChatUIKit } from "@cometchat/chat-uikit-react"; const UID = "UID"; // Replace with your actual UID CometChatUIKit.getLoggedinUser().then((user: CometChat.User | null) => { if (!user) { - // If no user is logged in, proceed with login CometChatUIKit.login(UID) .then((user: CometChat.User) => { console.log("Login Successful:", { user }); - // Mount your app }) .catch(console.log); } else { - // If user is already logged in, mount your app } }); ``` @@ -325,22 +186,19 @@ CometChatUIKit.getLoggedinUser().then((user: CometChat.User | null) => { -```js +```js lines highlight={3} import { CometChatUIKit } from "@cometchat/chat-uikit-react"; const UID = "UID"; // Replace with your actual UID CometChatUIKit.getLoggedinUser().then((user) => { if (!user) { - // If no user is logged in, proceed with login CometChatUIKit.login(UID) .then((user) => { console.log("Login Successful:", { user }); - // Mount your app }) .catch(console.log); } else { - // If user is already logged in, mount your app } }); ``` @@ -349,134 +207,64 @@ CometChatUIKit.getLoggedinUser().then((user) => { -*** - -### **Step 5: Choose a Chat Experience** - -Integrate a conversation view that suits your application's **UX requirements**. Below are the available options: + -*** + -#### **1️⃣ Conversation List + Message View** +Three layout options: -**Best for:** Applications that need a **two-panel layout**, such as web-based chat interfaces (e.g., WhatsApp Web, Slack). +#### Conversation List + Message View -**Features:** - -* **Two-panel layout** – Displays the conversation list on the left and the active chat window on the right. -* **One-to-one & group conversations** – Seamless switching between private and group chats. -* **Multiple conversations** – Effortlessly switch between different chat windows. -* **Easy navigation** – Intuitive UI for finding and accessing chats quickly. -* **Tap-to-view on mobile** – In mobile layouts, tapping a conversation opens the **Message View**, optimizing space. -* **Real-time updates** – Auto-refreshes messages and conversation lists. -* **Message sync** – Ensures messages stay updated across all sessions and devices. +Two-panel layout: conversation list on the left, active chat on the right. Supports 1:1 and group conversations with real-time updates. -**Recommended for:** - -* Desktop-first applications -* Apps requiring a **rich user experience** with seamless navigation -* Platforms supporting both **individual and group messaging** -* **Mobile-friendly** apps needing a **tap-to-open message view** - [](https://link.cometchat.com/react-conversation-list-message) -> **Tip:** You can **fork** the sandbox, insert your **CometChat credentials** (App ID, Region, Auth Key.) in the code, and immediately preview how the UI and messages respond in real time. - [Integrate Conversation List + Message](./react-conversation) -*** - -#### **2️⃣ One-to-One/Group Chat** +#### One-to-One/Group Chat -**Best for:** Apps that require a **focused, direct messaging experience** without a sidebar. - -**Features:** - -* **Dedicated chat window** – Ideal for one-on-one or group messaging. -* **No conversation list** – Users directly enter the chat without navigating through a list. -* **Supports both One-to-One and Group Chats** – Easily configurable with minor code modifications. -* **Optimized for mobile** – Full-screen chat experience without distractions. -* **Seamless real-time communication** – Auto-updates messages for a smooth experience. -* **Ideal for support chat or community-based messaging.** +Single chat window without a conversation list. Supports both 1:1 and group messaging. -**Recommended for:** - -* **Support chat applications** – Direct user-agent communication. -* **Apps focusing on direct messaging** – No distractions from other conversations. -* **Community or group chat applications** – A structured way to interact in groups. -* **Mobile-first applications** – Designed for compact and dedicated messaging experiences. - [](https://link.cometchat.com/react-one-on-one) -> **Tip:** You can **fork** the sandbox, insert your **CometChat credentials** (App ID, Region, Auth Key.) in the code, and immediately preview how the UI and messages respond in real time. - [Integrate One-to-One/Group Chat](./react-one-to-one-chat) -*** +#### Tab-Based Chat Experience -#### **3️⃣ Tab-Based Chat Experience** - -**Best for:** Apps that need a **structured, multi-feature navigation system** for seamless interaction between **chats, calls, users, and settings**. - -**Features:** - -* **Tab Navigation** – Easily switch between **Chat, Call Logs, Users, and Settings**. -* **Dedicated Chat Window** – Full-screen messaging experience for focused communication. -* **No Sidebar** – Unlike multi-panel UI, this design prioritizes individual interactions. -* **Unified Experience** – Users can seamlessly manage conversations, call history, and settings from a single interface. -* **Scalable for future features** – Easily extend to include more functionalities such as notifications or contact management. -* **Optimized for both desktop and mobile** – Ensures a smooth experience across different screen sizes. +Tab navigation between Chat, Call Logs, Users, and Settings. Works across desktop and mobile. -**Recommended for:** - -* **Apps requiring structured navigation** – Clearly separate chat, calls, and settings. -* **Multi-feature chat apps** – Supporting different functionalities in an organized way. -* **Mobile-first applications** – Ideal for apps needing tab-based UI for easy access to features. -* **Support & enterprise chat solutions** – Perfect for help desks, business chat platforms, and customer support apps. - [](https://link.cometchat.com/react-tabs-sidebar-message) -> **Tip:** You can **fork** the sandbox, insert your **CometChat credentials** (App ID, Region, Auth Key.) in the code, and immediately preview how the UI and messages respond in real time. - [Integrate Tab-Based Chat](./react-tab-based-chat) -*** - -## **Build Your Own Chat Experience** - -**Best for:** Developers who need complete control over their chat interface, allowing customization of components, themes, and features to align with their app’s design and functionality. Whether you're enhancing an existing chat experience or building from scratch, this approach provides the flexibility to tailor every aspect to your needs. - -**Recommended for:** - -* Apps that require **a fully customized chat experience**. -* Developers who want to **extend functionalities and modify UI components**. -* Businesses integrating chat seamlessly into **existing platforms**. + + -**Key Areas to Explore:** +## Build Your Own Chat Experience -* **[React Sample App](https://github.com/cometchat/cometchat-uikit-react/tree/v6/sample-app)** – Fully functional sample applications to accelerate your development. -* **[Core Features](./core-features)** – Learn about messaging, real-time updates, and other essential capabilities. -* **[Components](./components-overview)** – Utilize prebuilt UI elements or customize them to fit your design. -* **[Themes](./theme)** – Adjust colors, fonts, and styles to match your branding. -* **[Build Your Own UI](./../../../sdk/javascript/overview)** – Prefer a custom UI over our UI Kits? Explore our SDKs to create a tailored chat experience. +For full control over the chat interface, use individual components directly: -*** +* [React Sample App](https://github.com/cometchat/cometchat-uikit-react/tree/v6/sample-app) +* [Core Features](./core-features) +* [Components](./components-overview) +* [Themes](./theme) +* [Build with SDK](./../../../sdk/javascript/overview) ## iFrame Support -If you’re embedding your React app inside an `