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

# React.js Integration

> Add CometChat to a React.js app in 4 steps: create project, install, init + login, render.

<Accordion title="AI Integration Quick Reference">
  | Field            | Value                                                                                                                                           |
  | ---------------- | ----------------------------------------------------------------------------------------------------------------------------------------------- |
  | Package          | `@cometchat/chat-uikit-react` v7.0.x                                                                                                            |
  | Peer deps        | `react` >=18, `react-dom` >=18, `@cometchat/chat-sdk-javascript` ^4.1.9, `dompurify` ^3.3.1                                                     |
  | Init             | `CometChatUIKit.init(UIKitSettings)` — must resolve before `login()`                                                                            |
  | Login            | `CometChatUIKit.login("UID")` — must resolve before rendering components                                                                        |
  | Order            | `init()` → `login()` → render `<CometChatProvider>`. Breaking this order = blank screen                                                         |
  | Auth Key         | Dev/testing only. Use Auth Token in production                                                                                                  |
  | Calling          | Optional. Install `@cometchat/calls-sdk-javascript` and call `.setCallingEnabled(true)` on `UIKitSettingsBuilder`                               |
  | Other frameworks | [Next.js](/ui-kit/react/integration-nextjs) · [React Router](/ui-kit/react/integration-react-router) · [Astro](/ui-kit/react/integration-astro) |
</Accordion>

This guide walks you through adding CometChat to a React.js app. By the end you'll have a working chat UI.

<Frame>
  <img src="https://mintcdn.com/cometchat-22654f5b-docs-skills-v5-temp/dX_L5sxrV9HECPV3/images/two_panel_layout_without_tabs_react_v7.png?fit=max&auto=format&n=dX_L5sxrV9HECPV3&q=85&s=9f8b74ea44a073b486d174537aaa676e" width="1440" height="800" data-path="images/two_panel_layout_without_tabs_react_v7.png" />
</Frame>

***

## Prerequisites

You need three things from the [CometChat Dashboard](https://app.cometchat.com/):

| Credential | Where to find it                                           |
| ---------- | ---------------------------------------------------------- |
| App ID     | Dashboard → Your App → Credentials                         |
| Auth Key   | Dashboard → Your App → Credentials                         |
| Region     | Dashboard → Your App → Credentials (e.g. `us`, `eu`, `in`) |

You also need **Node.js 18+** and npm/yarn installed.

<Warning>
  Auth Key is for development only. In production, generate Auth Tokens server-side via the REST API. Never ship Auth Keys in client code.
</Warning>

***

## Step 1 — Create a React Project

<Tabs>
  <Tab title="Vite (recommended)">
    ```bash theme={null}
    npm create vite@latest my-app -- --template react-ts
    cd my-app
    ```
  </Tab>

  <Tab title="Create React App">
    ```bash theme={null}
    npx create-react-app my-app --template typescript
    cd my-app
    ```
  </Tab>
</Tabs>

***

## Step 2 — Install the UI Kit

<Tabs>
  <Tab title="npm">
    ```bash theme={null}
    npm install @cometchat/chat-uikit-react @cometchat/chat-sdk-javascript dompurify
    ```
  </Tab>

  <Tab title="yarn">
    ```bash theme={null}
    yarn add @cometchat/chat-uikit-react @cometchat/chat-sdk-javascript dompurify
    ```
  </Tab>
</Tabs>

If you want voice/video calling, also install:

```bash theme={null}
npm install @cometchat/calls-sdk-javascript
```

***

## Step 3 — Initialize, Login, and Render

Call `CometChatUIKit.init()` and `CometChatUIKit.login()` before rendering your app. Then wrap your components in `CometChatProvider`.

For development, use one of the pre-created test UIDs:

`cometchat-uid-1` · `cometchat-uid-2` · `cometchat-uid-3` · `cometchat-uid-4` · `cometchat-uid-5`

```tsx title="src/main.tsx" theme={null}
import ReactDOM from "react-dom/client";
import { CometChatUIKit, UIKitSettingsBuilder } from "@cometchat/chat-uikit-react";
import App from "./App";

const settings = new UIKitSettingsBuilder()
  .setAppId("YOUR_APP_ID")
  .setRegion("YOUR_REGION")
  .setAuthKey("YOUR_AUTH_KEY")
  .subscribePresenceForAllUsers()
  .build();

CometChatUIKit.init(settings).then(async () => {
  await CometChatUIKit.login("cometchat-uid-1");
  ReactDOM.createRoot(document.getElementById("root")!).render(<App />);
});
```

```tsx title="src/App.tsx" theme={null}
import { useState } from "react";
import { CometChat } from "@cometchat/chat-sdk-javascript";
import {
  CometChatProvider,
  CometChatConversations,
  CometChatMessageHeader,
  CometChatMessageList,
  CometChatMessageComposer,
} from "@cometchat/chat-uikit-react";

function App() {
  const [chatUser, setChatUser] = useState<CometChat.User | undefined>();
  const [chatGroup, setChatGroup] = useState<CometChat.Group | undefined>();

  const handleConversationClick = (conversation: CometChat.Conversation) => {
    const entity = conversation.getConversationWith();
    if (conversation.getConversationType() === "user") {
      setChatUser(entity as CometChat.User);
      setChatGroup(undefined);
    } else {
      setChatGroup(entity as CometChat.Group);
      setChatUser(undefined);
    }
  };

  return (
    <CometChatProvider>
      <div style={{ display: "flex", height: "100vh" }}>
        <div style={{ width: 360, borderRight: "1px solid #eee" }}>
          <CometChatConversations onItemClick={handleConversationClick} />
        </div>
        <div style={{ flex: 1, display: "flex", flexDirection: "column" }}>
          {(chatUser || chatGroup) && (
            <>
              <CometChatMessageHeader user={chatUser} group={chatGroup} />
              <CometChatMessageList user={chatUser} group={chatGroup} />
              <CometChatMessageComposer user={chatUser} group={chatGroup} />
            </>
          )}
        </div>
      </div>
    </CometChatProvider>
  );
}

export default App;
```

`CometChatProvider` supplies theme, locale, plugin registry, and event context to all child components. Init and login must complete before the provider mounts. See the [CometChatProvider](/ui-kit/react/cometchat-provider) guide for all props.

<Note>
  For production, use `CometChatUIKit.loginWithAuthToken(token)` instead of `login(uid)`. Generate auth tokens server-side via the [REST API](/rest-api/chat-apis). Never ship auth keys in client code.
</Note>

<Note>
  By default, session data is stored in `localStorage`. To use `sessionStorage` instead, see [Setting Session Storage Mode](/ui-kit/react/methods#setting-session-storage-mode).
</Note>

***

## Step 4 — Run

```bash theme={null}
npm run dev
```

Open `http://localhost:5173` (Vite) or `http://localhost:3000` (CRA). You should see the conversation list on the left. Click a conversation to open the message panel.

<Frame>
  <img src="https://mintcdn.com/cometchat-22654f5b-docs-skills-v5-temp/dX_L5sxrV9HECPV3/images/two_panel_layout_without_tabs_react_v7.png?fit=max&auto=format&n=dX_L5sxrV9HECPV3&q=85&s=9f8b74ea44a073b486d174537aaa676e" width="1440" height="800" data-path="images/two_panel_layout_without_tabs_react_v7.png" />
</Frame>

***

## Layout & Sizing

The UI Kit components are `height: 100%` / flex-fill — they **fill their parent** rather than sizing to their content. If the host layout doesn't give them room, they collapse to a sliver or overflow. The bare `height: 100vh` in the example above is the minimum; keep these rules in mind:

* **Give the container a content-independent height *and* width.** Use `height: 100dvh` (or `100vh`) on the outer wrapper — not `min-height` or `auto`, which collapse to \~0px because the components have no intrinsic height.
* **Constrain flex children so they scroll instead of growing.** Add `min-height: 0` (and `overflow: hidden`) to flex columns that hold a message list; without it, a long list pushes the whole layout taller instead of scrolling internally.
* **Reset any app scaffold that caps `#root`.** A fresh Vite/CRA `#root` is often `max-width`-capped, centered, and padded (from the starter's `index.css`/`App.css`) — which renders the chat gutter-boxed. Clear those:
  ```css title="src/index.css" theme={null}
  #root {
    max-width: none;
    margin: 0;
    padding: 0;
    width: 100%;
    height: 100dvh;
  }
  ```
* **Don't put `transform` or `filter` on an ancestor.** Either property creates a new containing block that clips the kit's `position: fixed` overlays — context menus, the emoji keyboard, and the call screen.

### Responsive layout

The two-panel example is a fixed side-by-side layout, which squashes on a phone. On narrow viewports, show **one pane at a time** — the conversation list, then the message view with a back button. Drive it off a breakpoint:

```tsx theme={null}
import { useEffect, useState } from "react";

function useIsMobile(breakpoint = 768) {
  const [isMobile, setIsMobile] = useState(
    () => window.matchMedia(`(max-width: ${breakpoint}px)`).matches
  );

  useEffect(() => {
    const media = window.matchMedia(`(max-width: ${breakpoint}px)`);
    const onChange = () => setIsMobile(media.matches);
    media.addEventListener("change", onChange);
    return () => media.removeEventListener("change", onChange);
  }, [breakpoint]);

  return isMobile;
}
```

On mobile, render **either** the list **or** the message pane based on `isMobile` and whether a conversation is selected, and use `CometChatMessageHeader`'s built-in back button (it renders by default; wire `onBack` to clear the selection, or set `hideBackButton` to control it) to return to the list:

```tsx theme={null}
// Inside App, with `chatUser`/`chatGroup` state from the example above:
const isMobile = useIsMobile();
const hasSelection = Boolean(chatUser || chatGroup);

if (isMobile) {
  return (
    <CometChatProvider>
      <div style={{ height: "100dvh" }}>
        {!hasSelection ? (
          <CometChatConversations onItemClick={handleConversationClick} />
        ) : (
          <div style={{ display: "flex", flexDirection: "column", height: "100%" }}>
            <CometChatMessageHeader
              user={chatUser}
              group={chatGroup}
              onBack={() => {
                setChatUser(undefined);
                setChatGroup(undefined);
              }}
            />
            <CometChatMessageList user={chatUser} group={chatGroup} />
            <CometChatMessageComposer user={chatUser} group={chatGroup} />
          </div>
        )}
      </div>
    </CometChatProvider>
  );
}
```

***

## Choose a Chat Experience

### Conversation List + Message View

Two-panel layout — conversation list on the left, messages on the right.

<Frame>
  <img src="https://mintcdn.com/cometchat-22654f5b-docs-skills-v5-temp/dX_L5sxrV9HECPV3/images/two_panel_layout_without_tabs_react_v7.png?fit=max&auto=format&n=dX_L5sxrV9HECPV3&q=85&s=9f8b74ea44a073b486d174537aaa676e" width="1440" height="800" data-path="images/two_panel_layout_without_tabs_react_v7.png" />
</Frame>

***

### One-to-One / Group Chat

Single chat window — no sidebar. Good for support chat or embedded widgets.

<Frame>
  <img src="https://mintcdn.com/cometchat-22654f5b-docs-skills-v5-temp/dX_L5sxrV9HECPV3/images/one_panel_layout_react_v7.png?fit=max&auto=format&n=dX_L5sxrV9HECPV3&q=85&s=1351feacd2db5ecf690de2466f23110e" width="1440" height="800" data-path="images/one_panel_layout_react_v7.png" />
</Frame>

***

### Tab-Based Chat

Tabbed navigation — Chat, Call Logs, Users, Settings in separate tabs.

<Frame>
  <img src="https://mintcdn.com/cometchat-22654f5b-docs-skills-v5-temp/dX_L5sxrV9HECPV3/images/two_panel_layout_with_tabs_react_v7.png?fit=max&auto=format&n=dX_L5sxrV9HECPV3&q=85&s=516894daba05627d3960403043f0ffcf" width="1440" height="800" data-path="images/two_panel_layout_with_tabs_react_v7.png" />
</Frame>

***

## Build Your Own Chat Experience

Need full control over the UI? Use individual components, customize themes, and wire up your own layouts.

* [Sample App](https://github.com/cometchat/cometchat-uikit-react/tree/v7/sample-app) — Working reference app to compare against
* [Components](/ui-kit/react/components-overview) — All prebuilt UI elements with props and customization options
* [Core Features](/ui-kit/react/core-features) — Messaging, real-time updates, and other capabilities
* [Theming](/ui-kit/react/theming) — Colors, fonts, dark mode, and custom styling
* [Build Your Own UI](/sdk/javascript/overview) — Skip the UI Kit entirely and build on the raw SDK

***

## iFrame Embedding

If your React app runs inside an `<iframe>`, wrap your tree in `CometChatFrameProvider` so dialogs and portals mount in the correct frame:

```tsx theme={null}
import { CometChatFrameProvider } from "@cometchat/chat-uikit-react";

<CometChatFrameProvider iframeId="cometchat-frame">
  <App />
</CometChatFrameProvider>
```

| Prop       | Type     | Description                                   |
| ---------- | -------- | --------------------------------------------- |
| `iframeId` | `string` | The DOM `id` of the target `<iframe>` element |

***

## Next Steps

<CardGroup cols={2}>
  <Card title="Components Overview" icon="grid-2" href="/ui-kit/react/components-overview">
    Browse all prebuilt UI components
  </Card>

  <Card title="Theming" icon="paintbrush" href="/ui-kit/react/theming">
    Customize colors, fonts, and styles
  </Card>

  <Card title="Plugins" icon="puzzle-piece" href="/ui-kit/react/plugins/overview">
    Customize message rendering
  </Card>

  <Card title="Troubleshooting" icon="wrench" href="/ui-kit/react/troubleshooting">
    Common issues and fixes
  </Card>
</CardGroup>
