Skip to main content
List and select users with search and presence using the CometChatUsers component.

When to use this

  • You need a searchable list of users.
  • You want a user picker to start new chats.
  • You need to filter users by tags, roles, or status.

Prerequisites

  • CometChat React UI Kit v6 installed: @cometchat/chat-uikit-react.
  • CometChatUIKit.init() and CometChatUIKit.login() complete before rendering.

Quick start

  1. Add the component to your UI.
import React from "react";
import { CometChatUsers } from "@cometchat/chat-uikit-react";

export default function UsersDemo() {
  return <CometChatUsers />;
}
What this does: Renders the minimal version of the component.
  1. Verify the component renders after init() and login().

Core concepts

  • usersRequestBuilder controls filtering and paging.
  • selectionMode enables multi-select workflows.
  • onItemClick handles selection for navigation.

Implementation

  • Package: @cometchat/chat-uikit-react
  • Import: import { CometChatUsers } from "@cometchat/chat-uikit-react";
  • Minimal JSX: <CometChatUsers />
  • Required setup: CometChatUIKit.init(UIKitSettings) then CometChatUIKit.login("UID")
  • Key props: onItemClick: (user: CometChat.User) => void, selectionMode: SelectionMode, usersRequestBuilder: CometChat.UsersRequestBuilder, hideSearch: boolean, showSectionHeader: boolean
  • CSS class: .cometchat-users

Overview

What you’re changing: Overview. Where to change it: Component props or CSS as shown below. Default behavior: UI Kit defaults. Override: Use the examples in this section. Verify: The UI reflects the change shown below. The Users is a Component, showcasing an accessible list of all available users. It provides an integral search functionality, allowing you to locate any specific user swiftly and easily. For each user listed, the widget displays the user’s name by default, in conjunction with their avatar when available. Furthermore, it includes a status indicator, visually informing you whether a user is currently online or offline.
Before using this component: Ensure CometChatUIKit.init(UIKitSettings) has completed and the user is logged in via CometChatUIKit.login("UID"). See React.js Integration.
The Users component is composed of the following BaseComponents:
ComponentsDescription
CometChatListA reusable container component having title, search box, customisable background and a list view.
CometChatListItemA component that renders data obtained from a User object on a Tile having a title, subtitle, leading and trailing view.

Usage

What you’re changing: Usage. Where to change it: Component props or CSS as shown below. Default behavior: UI Kit defaults. Override: Use the examples in this section. Verify: The UI reflects the change shown below.

Integration

The following code snippet illustrates how you can directly incorporate the Users component into your Application.
import { CometChatUsers } from "@cometchat/chat-uikit-react";

function UsersDemo() {
  return <CometChatUsers />;
}

export default UsersDemo;
What this does: Shows the code for this step.

Actions

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. onSelect
The onSelect action is activated when you select the done icon while in selection mode. This returns a list of all the users 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.
import { CometChatUsers, SelectionMode } from "@cometchat/chat-uikit-react";

function UsersDemo() {
  function handleOnSelect(users: CometChat.User, selected: boolean): void {
    console.log(users);
    //your custom onSelect actions
  }

  return (
    <CometChatUsers
      selectionMode={SelectionMode.multiple}
      onSelect={handleOnSelect}
    />
  );
}

export default UsersDemo;
What this does: Shows the code for this step.
2. onItemClick
The OnItemClick event is activated when you click on the UserList 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.
import { CometChatUsers } from "@cometchat/chat-uikit-react";

function UsersDemo() {
  function handleOnItemClick(user: CometChat.User): void {
    console.log(user, "your custom on item click action");
  }
  return <CometChatUsers onItemClick={handleOnItemClick} />;
}

export default UsersDemo;
What this does: Shows the code for this step.
3. onEmpty
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.
import { CometChatUsers } from "@cometchat/chat-uikit-react";

function UsersDemo() {
  function handleOnEmpty(): void {
    console.log("your custom on Empty action");
  }
  return <CometChatUsers onEmpty={handleOnEmpty} />;
}

export default UsersDemo;
What this does: Shows the code for this step.
4. onError
This action doesn’t change the behavior of the component but rather listens for any errors that occur in the User component.
import { CometChatUsers } from "@cometchat/chat-uikit-react";

function UsersDemo() {
  const handleOnError = (error: CometChat.CometChatException) => {
    console.log("Your custom on error actions");
  };
  return <CometChatUsers onError={handleOnError} />;
}

export default UsersDemo;
What this does: Shows the code for this step.

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. UserRequestBuilder
The UserRequestBuilder enables you to filter and customize the user list based on available parameters in UserRequestBuilder. This feature allows you to create more specific and targeted queries when fetching users. The following are the parameters available in UserRequestBuilder
MethodsTypeDescription
setLimitnumbersets the number users that can be fetched in a single request, suitable for pagination
setSearchKeywordStringused for fetching users matching the passed string
hideBlockedUsersbooleanused for fetching all those users who are not blocked by the logged in user
friendsOnlybooleanused for fetching only those users in which logged in user is a member
setRolesList<String>used for fetching users containing the passed tags
setTagsList<String>used for fetching users containing the passed tags
withTagsbooleanused for fetching users containing tags
setStatusStringused for fetching users by their status online or offline
setUIDsList<String>used for fetching users containing the passed users
Example In the example below, we are applying a filter to the UserList based on Friends.
import { CometChat } from "@cometchat/chat-sdk-javascript";
import { CometChatUsers } from "@cometchat/chat-uikit-react";

function UsersDemo() {
  return (
    <CometChatUsers
      usersRequestBuilder={new CometChat.UsersRequestBuilder().friendsOnly(
        true
      )}
    />
  );
}

export default UsersDemo;
What this does: Shows the code for this step.
2. SearchRequestBuilder
The SearchRequestBuilder uses UserRequestBuilder enables you to filter and customize the search list based on available parameters in UserRequestBuilder. This feature allows you to keep uniformity between the displayed UserList and searched UserList. Example
import { CometChat } from "@cometchat/chat-sdk-javascript";
import { CometChatUsers } from "@cometchat/chat-uikit-react";

function UsersDemo() {
  return (
    <CometChatUsers
      searchRequestBuilder={new CometChat.UsersRequestBuilder().setSearchKeyword(
        "**"
      )}
    />
  );
}

export default UsersDemo;
What this does: Shows the code for this step.

Events

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 Users you have to add corresponding listeners by using CometChatUserEvents The Users component does not produce any events directly.

Customization

What you’re changing: Customization. Where to change it: Component props or CSS as shown below. Default behavior: UI Kit defaults. Override: Use the examples in this section. Verify: The UI reflects the change shown below. To fit your app’s design requirements, you can customize the appearance of the Users component. We provide exposed methods that allow you to modify the experience and behavior according to your specific needs.

Style

Using CSS you can customize the look and feel of the component in your app like the color, size, shape, and fonts. Example
import { CometChatUsers } from "@cometchat/chat-uikit-react";

function UsersDemo() {
  return <CometChatUsers showSectionHeader={false} />;
}

export default UsersDemo;
What this does: Shows the code for this step.

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.
import { CometChatUsers, TitleAlignment } from "@cometchat/chat-uikit-react";

function UsersDemo() {
  return (
    <CometChatUsers
      title="Your Custom Title"
      showSectionHeader={true}
      tileAlignment={TitleAlignment.center}
    />
  );
}

export default UsersDemo;
What this does: Shows the code for this step.
Below is a list of customizations along with corresponding code snippets
PropertyDescriptionCode
Hide SearchHides the default search bar.hideSearch={true}
Show Section HeaderDisplays an alphabetical section header for the user list.showSectionHeader={true}
Hide ErrorHides both the default and custom error view passed in errorView prop.hideError={true}
Hide User StatusHides the user’s online/offline status indicator.hideUserStatus={true}
Active UserThe user to be highlighted in the users list.activeUser={chatUser}
Search KeywordThe search keyword used to filter the user list.searchKeyword="Alice"
Section Header KeyThe property on the user object used to extract the section header character.sectionHeaderKey={getName}
Selection ModeSelection mode to use for the default trailing view.selectionMode={SelectionMode.multiple}
Show ScrollbarControls the visibility of the scrollbar in the list.showScrollbar={true}
Loading ViewA custom view to display during the loading state.loadingView={<>Custom Loading View</>}
Empty ViewA custom view to display when no users are available in the list.emptyView={<>Custom Empty View</>}
Error ViewA custom view to display when an error occurs.errorView={<>Custom Error View</>}
Show Selected Users PreviewShows a preview of selected users when selectionMode is multiple.showSelectedUsersPreview={true}

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.
ItemView
A custom view to render for each user in the fetched list. Shown below is the default chat interface.
The customized chat interface is displayed below.
Use the following code to achieve the customization shown above.
import { CometChat } from "@cometchat/chat-sdk-javascript";
import { CometChatUsers } from "@cometchat/chat-uikit-react";

function UsersDemo() {
  const getItemView = (user: CometChat.User) => {
    const status = user.getStatus();

    return (
      <div
        className={`cometchat-users__list-item cometchat-users__list-item-${status}
          ${status === "online" ? `cometchat-users__list-item-active` : ""}
          `}
      >
        <CometChatListItem
          title={user.getName()}
          subtitleView={user.getStatus()}
          avatarURL={user.getAvatar()}
          avatarName={user.getName()}
        />
      </div>
    );
  };

  return <CometChatUsers itemView={getItemView} />;
}

export default UsersDemo;
What this does: Shows the code for this step.

TitleView
The customized chat interface is displayed below.
Use the following code to achieve the customization shown above.
import React from "react";
import { CometChat } from "@cometchat/chat-sdk-javascript";
import { CometChatUsers } from "@cometchat/chat-uikit-react";

// Custom title view component
 const customTitleView = (user: CometChat.User) => {
    return <div className={`users__title-view users__title-view-${user.getRole()}`}>
      <span className="users__title-view-name">{user.getName()}</span>
      <span className="users__title-view-type"><img src="ICON_HERE"></img>{user.getRole()}</span>
     </div>;
  }

<CometChatUsers titleView={customTitleView} />;
What this does: Shows the code for this step.

SubtitleView
A custom view to render the subtitle for each user. Shown below is the default chat interface.
The customized chat interface is displayed below.
Use the following code to achieve the customization shown above.
import { CometChat } from "@cometchat/chat-sdk-javascript";
import { CometChatUsers } from "@cometchat/chat-uikit-react";

function UsersDemo() {
  function formatTime(timestamp: number) {
    const date = new Date(timestamp * 1000);
    return date.toLocaleString();
  }

  const getSubtitleView = (user: CometChat.User): JSX.Element => {
    if (!(user instanceof CometChat.User)) {
      return <></>;
    }

    return (
      <div className="users-subtitle">
        Last Active At: {formatTime(user.getLastActiveAt())}
      </div>
    );
  };

  return <CometChatUsers subtitleView={getSubtitleView} />;
}

export default UsersDemo;
What this does: Shows the code for this step.

HeaderView
You can set the Custom headerView to add more options to the Users component. The customized chat interface is displayed below.
Use the following code to achieve the customization shown above.
import { CometChat } from "@cometchat/chat-sdk-javascript";
import { CometChatUsers,localize,CometChatButton } from "@cometchat/chat-uikit-react";
import React from "react";

const getHeaderView = () => {
    return (
        <div className="cometchat-users__header">
            <div className="cometchat-users__header__title">
                {localize("USERS")}
            </div>
            <CometChatButton 
                onClick={() => {
                    // logic here
                }}
                iconURL={ICON_URL} 
            />
        </div>
    );
};

<CometChatUsers headerView={getHeaderView()} />
What this does: Shows the code for this step.

LeadingView
The customized chat interface is displayed below.
Use the following code to achieve the customization shown above.
import React from "react";
import { CometChat } from "@cometchat/chat-sdk-javascript";
import { CometChatUsers,CometChatAvatar } from "@cometchat/chat-uikit-react";

const customLeadingView = (user: CometChat.User): JSX.Element => {
    return (
      <div className={`users__leading-view users__leading-view-${user.getRole()}`}>
        <CometChatAvatar 
          image={user?.getAvatar()} 
          name={user?.getName()} 
        />
        <span className="users__leading-view-role"><img src={"ICON_URL"}/></span>
      </div>
    );
  };
<CometChatUsers leadingView={customLeadingView} />
What this does: Shows the code for this step.

TrailingView
The customized chat interface is displayed below.
Use the following code to achieve the customization shown above.
import React from "react";
import { CometChat } from "@cometchat/chat-sdk-javascript";
import {
  CometChatUsers,
} from "@cometchat/chat-uikit-react";

const customTrailingButtonView = (user:CometChat.User) =>  {
  let tag = user?.getTags() ? user?.getTags()[0] : "";
  return <div className="users__trailing-view">
   <span className="users__trailing-view-icon">
   <img src="ICON_HERE"/>
   </span>
   <span className="users__trailing-view-text">{tag}</span>
  </div>
}

<CometChatUsers  trailingView={customTrailingButtonView} />;
What this does: Shows the code for this step.

Options
A function that returns a list of actions available when hovering over a user item. Shown below is the default chat interface.
The customized chat interface is displayed below.
Use the following code to achieve the customization shown above.
import { CometChatUsers, CometChatOption } from "@cometchat/chat-uikit-react";

function UsersDemo() {
  const getOptions = (user: CometChat.User): CometChatOption[] => {
    return [
      new CometChatOption({
        id: "delete",
        title: "delete",
        onClick: () => {
          console.log("Custom option clicked for user:", user);
        },
      }),
    ];
  };

  return <CometChatUsers options={getOptions} />;
}

export default UsersDemo;
What this does: Shows the code for this step.

Component API Pattern

What you’re changing: Component API Pattern. Where to change it: Component props or CSS as shown below. Default behavior: UI Kit defaults. Override: Use the examples in this section. Verify: The UI reflects the change shown below.
Customization TypeProp PatternExample
Callback actionson<Event>={(param) => {}}onItemClick={(user) => {}}
Data filteringusersRequestBuilder={new CometChat.UsersRequestBuilder()}usersRequestBuilder={builder}
Toggle featureshide<Feature>={true|false}hideSearch={true}
Custom rendering<slot>View={(<params>) => JSX}itemView={(user) => <div>...</div>}
CSS overridesTarget .cometchat-users class in global CSS.cometchat-users { ... }
SymptomCauseFix
Component doesn’t renderCometChatUIKit.init() not called or not awaitedEnsure init completes before rendering. See Methods
Component renders but shows no dataUser not logged inCall CometChatUIKit.login("UID") after init
Callback not firingWrong prop name or signatureCheck the Actions section for exact prop name and parameter types
Custom view not appearingReturning null or undefined from view propEnsure view function returns valid JSX
SSR hydration errorComponent uses browser APIs on serverWrap in useEffect or dynamic import with ssr: false. See Next.js Integration

Customization matrix

What you want to changeWhereProperty/APIExample
Handle item clickCometChatUsersonItemClickonItemClick={(u) => setActive(u)}
Enable multi-selectCometChatUsersselectionModeselectionMode={SelectionMode.multiple}
Filter usersCometChatUsersusersRequestBuildernew CometChat.UsersRequestBuilder().friendsOnly(true)
Hide searchCometChatUsershideSearchhideSearch={true}

Common pitfalls and fixes

SymptomCauseFix
Component does not renderInit/login not completeCall CometChatUIKit.init() and login() first
List is emptyFilters too strictRelax usersRequestBuilder filters
Search shows no resultsSearch builder too restrictiveAdjust searchRequestBuilder
Callbacks not firingWrong prop nameUse onItemClick or onSelect
Styles not applyingCSS Modules usedUse global CSS with .cometchat-users

FAQ

Can I hide the search bar? Yes. Set hideSearch={true}. How do I filter users by status? Use UsersRequestBuilder().setStatus(...).

Next steps