Chat UIKit React v2
Chat UIKit React
Chat UIKit
React
Version 2
Sendbird Chat UIKit v2 for React is no longer supported as a new version is released. Check out our latest Chat UIKit v3

Group channel

Copy link

This page explains key functions of group channels in Sendbird UIKit for React consisting of how to list channels, chat in a channel, configure channel settings, create a channel, and invite users.


Customize the user list

Copy link

When creating a channel or inviting users to a channel, UIKit shows the user list page to enable user selection. The customized user list can be retrieved by using the UserListQuery which should be implemented in the SendBirdProvider. If not, all the users in the application are retrieved through the Chat SDK’s ApplicationUserListQuery by default. Implement the UserListQuery as follows:

interface UserListQuery {
    hasNext: boolean;
    next(callback): void;
}

Implement the interface as follows:

// A member must have these three properties and the userId must be unique.
const Member = () => ({
    userId,
    profileUrl,
    nickname,
});

class CustomUserPaginatedQuery {
    constructor() {
        // Required public property to determine if more data is available.
        this.hasNext = false;
    }

    // Required public property.
    next(callback) {
        // Make async call and get list of users
        const [users, error] = myAsyncCallToGenerateMembers();
        // Set this.hasNext
        this.hasNext = setTrueIfMoreMembersCanBeFetched();
        callback(users, error);
    }
}

const CustomUserPaginatedQueryFactory = () => new CustomUserPaginatedQuery();

Apply the query as follows:

import { App } from "sendbird-uikit";
import "sendbird-uikit/dist/index.css";

const MyApp = () => {
    <Route id={'/chat'}>
        <App userId={userId} appId={appId} userListQuery={CustomUserPaginatedQueryFactory} />
    </div>
}

List channels

Copy link

You can list channels by using the ChannelList component. Once a client app is connected to Sendbird server, the list of channels in the client app will be displayed by passing the ChannelList.

How to use

Copy link

In order to use the ChannelList, it must be included in the SendBirdProvider. If the SendBirdProvider is placed at the top level, you can use the ChannelList anywhere in your application. The ChannelList has no minimum height and follows the height of the container, so it is recommended to specify the height of the wrapper element to fit your needs.

Create a channel

Copy link

Creating a channel is a two-step process.

  1. Select a channel type to create.

  1. Select users to invite to the new channel.

To create a Supergroup channel, you have to set allow_super_group_channel to true first through Chat Platform API or in the Sendbird Dashboard. The user who created a new channel becomes an operator of the channel. More operators can be added to the channel through the ChannelSettings component or the onBeforeCreateChannel method.


The Create channel icon can also be hidden from the view by adding the following rule to your CSS:

.sendbird-channel-header__right-icon {
    display: none;
}

List of properties

Copy link
Optional
Property nameTypeDescription

renderChannelPreview

ReactElement

A custom component to replace the default channelPreview component. The following are given as arguments:
- channel: GroupChannel
- onLeaveChannel: function(channel, callback)

onChannelSelect

function

The prop to execute custom operations when listing the group channels selected by the current user. (Default: null)

onBeforeCreateChannel

function

The prop to execute custom operations before creating a channel.
- Function signature: fn(selectedUsers) => { return GroupChannelParams }

sortChannelList

function

A function to sort the channels in the UI. You shouldn't add or remove channels from the ChannelList array when using this function.
- Function signature: fn(channels: BaseChannel) => { ... return sortedChannels: BaseChannel }

allowProfileEdit

boolean

Determines whether to allow the user to edit their profile. (Default: false)

onProfileEditSuccess

function

The prop to receive callback when a user profile has been successfully edited.

queries.channelListQuery

instance

A GroupChannelListQuery instance to filter channels by using its options.

queries.applicationUserListQuery

instance

An ApplicationUserListQuery instance to retrieve users when creating a channel.

Note : Static methods and keys such as next() or hasMore should not be overriden when customizing queries.

The sample codes below show how to implement ChannelList with its properties.

renderChannelPreview&moreonBeforeCreateChannelsortChannelListqueries.channelListQuery&more
// renderChannelPreview & onChannelSelect
import { ChannelList, SendBirdProvider} from "sendbird-uikit";
import "sendbird-uikit/dist/index.css";

const MyCustomPreview = ({ channel, onLeaveChannel }) => (
    <div style={{ border: '1px solid gray' }}>
        <img height="20px" width="20px" src={channel.coverUrl} />
        <button onClick={() => {
            const callback = () => {
                console.warn('Leave channel success')
            };
            onLeaveChannel(channel, callback);
            }}
            > Leave
        </button>
    </div>
);

const App = () => (
    <SendBirdProvider appId={appId} userId={userId}>
        <div style={{ height: '520px' }}>
            <ChannelList renderChannelPreview={MyCustomPreview}
                onChannelSelect={(channel) => { console.warn(channel); }}
            />
        </div>
    </SendBirdProvider>
);

Chat in a channel

Copy link

Configure to display channel messages using the Channel component. Similar to the ChannelList, the Channel component also must be included in the SendBirdProvider. If you place the SendBirdProvider on the top level, you can use the Channel anywhere in your application. The Channel has no minimum height and follows the height of the container, so it is recommended to specify the height of the wrapper element to fit your needs.

For messages, users can send plain text, image, video, and file messages. Once sent, those messages are grouped by time and date, displaying time boundaries in the chat view.

Note: A channel member can't enter a message when a channel is frozen, or they are muted users, or the Chat SDK can't connect to Sendbird server due to network errors.

How to use

Copy link

Use the following code to import Channel:

import { Channel } from "sendbird-uikit";

List of properties

Copy link
RequiredTypeDescription

channelUrl

string

The unique URL of the channel.

OptionalTypeDescription

renderChatItem

ReactElement

An element used to customize the rendering of all kinds of messages. The following are given as arguments:
- message: BaseMessage
- onUpdateMessage: function(messageId, message, callback)
- onDeleteMessage: function(message, callback)
- channel: GroupChannel

renderCustomMessage

ReactElement

A custom element to replace certain message types. The following are given as arguments:
- message: BaseMessage
- channel: GroupChannel
- chainTop: boolean
- chainBottom: boolean

renderChatHeader

ReactElement

A custom header to replace the default channel header. The following are given as arguments:
- channel: GroupChannel, user: User

renderMessageInput

ReactElement

A custom input to replace the default message input. The following are given as arguments:
- channel: GroupChannel, user: User, disabled: Boolean, quotedMessage: UserMessage or FileMessage

renderUserProfile

ReactElement

Renders a customized user profile preview section when clicking on the avatar. The following are given as arguments:
- user: User, currentUserId: userId, close: function

onChatHeaderActionClick

function

The prop to execute custom operations when the top-right icon on the header has been clicked. (Default: null)

onBeforeSendUserMessage

function

The prop to execute additional operations to a user message. The modified user message is returned through UserMessageParams before sending it.
- Function signature: fn(text, quotedMessage) => { return UserMessageParams }

onBeforeSendFileMessage

function

The prop to execute additional operations to a file message. The modified file message is returned through FileMessageParams before sending it.
- Function signature: fn(file, quotedMessage) => { return FileMessageParams }

onBeforeUpdateUserMessage

function

The prop to execute additional operations for a user message before updating it.
- Function signature: fn(text) => { return UserMessageParams }

queries.messageListParams

instance

A query instance to retrieve a list of messages by specifying the properties of MessageListParams.

useMessageGrouping

boolean

A function to group messages based on the time the messages were sent. If a user sends multiple messages in one minute, those messages will be grouped and the time when they were sent will be displayed once, next to the last message.

highlightedMessage

string or number

The ID of the highlighted message (Default: null)

startingPoint

number

The timestamp of the first message in the returned message list. If you change this value, the message list is fetched again.

showSearchIcon

boolean

Determines whether to show the search icon in the channel title. (Default: false)

onSearchClick

function

The prop to execute custom operations when the search icon on the header is clicked. (Default: null)

disableUserProfile

boolean

Determines whether to display the profile preview section when clicking on the avatar. If set to true, the profile preview section is not shown. (Default: false)

The sample codes below show how to render a custom view of the Channel.

renderChatItemrenderChatHeaderrenderMessageInput
import { Channel, SendBirdProvider } from "sendbird-uikit";
import "sendbird-uikit/dist/index.css";

const MyCustomChatMessage = ({ message, onDeleteMessage, onUpdateMessage }) => (
    <div>
        {message.message}
        <button onClick={() => {
            const callback = () => { console.warn('message deleted'); }
            onDeleteMessage(message, callback);
            }}
            > Delete
        </button>
        <button onClick={() => {
            const updatedMessage = Math.random().toString();
            const callback = () => { console.warn('message updated'); }
            onUpdateMessage(message.messageId, updatedMessage, callback);
            }}
            > Update
        </button>
    </div>
);

const App = () => (
    <SendBirdProvider appId={appId} userId={userId}>
        <div style={{ height: '500px' }}>
            <Channel channelUrl={channelUrl} renderChatItem={MyCustomChatMessage} />
        </div>
    </SendBirdProvider>
);

The sample codes below show how to implement Channel with various properties.

onBeforeSendUserMessage&morequeries.messageListParamschannelSearchIcon
// onBeforeSendUserMessage & onBeforeSendFileMessage & onBeforeUpdateUserMessage
const ChannelWithOnBeforeActions = ({ sdk }) => (
    <div style={{ height: '520px' }}>
        <Channel channelUrl={channelUrl}
            onBeforeSendUserMessage={(text) => {
                const params = new sdk.UserMessageParams();
                params.message = text + EXTRA_MESSAGE;
                params.data = DATA;
                return params;
            }}
            onBeforeSendFileMessage={(file) => {
                const params = new sdk.FileMessageParams();
                params.file = file;
                params.data = DATA;
                return params;
            }}
            onBeforeUpdateUserMessage={(text) => {
                const params = new sdk.UserMessageParams();
                params.message = text + MESSAGE_TO_UPDATE;
                params.data = DATA;
                return params;
            }}
        />
    </div>
)

const ConnectedChannel = withSendBird(ChannelWithOnBeforeActions, (store) => ({
    sdk: getSdk(store),
}))

export const OnBeforeActionsChannel = () => (
    <Sendbird appId={appId} userId={userId}> <ConnectedChannel />
    </Sendbird>
);

Invite users

Copy link

Custom user list can be implemented to the chat to create a new group chat or an 1-on-1 chat. You can also implement how to invite new members to your chat.

The ApplicationUserListQuery is used to invite users by default. Another way to invite users is fetching data to the App or SendBirdProvider components by passing a function. The implementation can be done by following the below sample code:

// A member must have these three properties and userId must be unique
const Member = () => ({
    userId,
    profileUrl,
    nickname,
});

class CustomUserPaginatedQuery {
    constructor() {
        // Required public property to determine if more data is available.
        this.hasNext = false;
    }

    // Required public property
    next(callback) {
        // Make an async call and get list of users.
        const [users, error] = myAsyncCallToGenerateMembers();
        // Set this.hasNext
        this.hasNext = setTrueIfMoreMembersCanBeFetched();
        callback(users, error);
    }
}

const getCustomPaginatedQuery = () => new CustomPaginatedQuery();

import { App } from "sendbird-uikit";
import "sendbird-uikit/dist/index.css";

const MyApp = () => {
    <Route id={'/chat'}>
        <App userId={userId} appId={appId} userListQuery={getCustomPaginatedQuery} />
    </div>
}

Search messages

Copy link

In UIKit for React, you can use this component with other UIKit components to implement a search system within your application.

How to use

Copy link

Use the following code to import MessageSearch.

import { MessageSearch } from "sendbird-uikit";

List of properties

Copy link
RequiredTypeDescription

channelUrl

string

The unique URL of the channel to search for. (Default: null)

searchString

string

The string of the message to search for. We recommend limiting the number of changes to this value to prevent an overload of search being carried out. (Default: null)

OptionalTypeDescription

onResultLoaded

function

The prop to execute custom operations when searched messages are fetched. (Default: null)

onResultClick

function

The prop to execute custom operations when a search result is clicked. (Default: null)

messageSearchQuery

instance

A MessageSearchQuery instance in MessageSearch to customize query operations. (Default: null)

renderSearchItem

ReactElement

Customizes the view of the searched message. (Default: null)

The sample codes below show how to implement MessageSearch with its properties.

messageSearchPanelmessageSearchExample
import React, { useState, useContext, useEffect } from 'react';


import { MessageSearch } from 'sendbird-uikit';;

const COMPONENT_CLASS_NAME = 'sendbird-message-search-panel';

function MessageSearchPanel() {
    const {
        channelUrl,
        onResultClick,
        onCloseClick,
    } = props;

    const [searchString, setSearchString] = useState('');
    const [inputString, setInputString] = useState('');
    const [loading, setLoading] = useState(false);
    const { stringSet } = useContext(LocalizationContext);

    let timeout = null;
    useEffect(() => {
        if (timeout) {
            clearTimeout(timeout);
        }
        timeout = setTimeout(() => {
            setSearchString(inputString);
            setLoading(true);
            timeout = null;
        }, 500);
    }, [inputString]);

    const handleOnChangeInputString = (e) => {
        setInputString(e.target.value);
    };

    const handleOnResultLoaded = (messages, error) => {
        setLoading(false);
    };

    const handleOnClickResetStringButton = (e) => {
        e.stopPropagation();
        setInputString('');
        setSearchString('');
    };

    return (
        <div className={COMPONENT_CLASS_NAME}>
            <div className={`${COMPONENT_CLASS_NAME}__header`}>
                <h1>
                    Search in channel
                    <button
                        onClick={onCloseClick}
                    >x</button>
                </h1>
            </div>
            <div className={`${COMPONENT_CLASS_NAME}__input`}>
                <div className={`${COMPONENT_CLASS_NAME}__input__container`}>
                    <input
                        className={`${COMPONENT_CLASS_NAME}__input__container__input-area`}
                        placeholder={stringSet.SEARCH}
                        value={inputString}
                        onChange={handleOnChangeInputString}
                    />
                    {
                        inputString && loading && (
                            // Implement your loader here.
                        )
                    }
                    {
                        !loading && inputString && (
                            // Implement your reset icon here.
                        )
                    }
                </div>
            </div>
            <div className={`${COMPONENT_CLASS_NAME}__message-search`}>
                <MessageSearch
                    channelUrl={channelUrl}
                    searchString={searchString}
                    onResultClick={onResultClick}
                    onResultLoaded={handleOnResultLoaded}
                />
            </div>
        </div>
    );
}

Configure channel settings

Copy link

Use the ChannelSettings component to show a list of channels or create a channel. Similar to the ChannelList and Channel, the ChannelSettings component also must be included in the SendBirdProvider. When the height of your wrapper component is specified, the ChannelList will assume this height. If you want to adjust width or other visual properties, you may need to use CSS.

The Channel settings view will differ by user type:

Regular users

Copy link

Operators

Copy link

For operators, the Channel settings include the following moderation actions:

  • Add and remove operators
  • Mute and unmute members
  • Ban and unban members
  • Freeze and unfreeze members

CSS selectors for each moderation operation

Copy link
OperationCSS selector class

Members

sendbird-channel-settings__members

Operators

sendbird-channel-settings__operators-list

Banned members list

sendbird-channel-settings__banned-members-list

Muted members list

sendbird-channel-settings__muted-members-list

Freeze/Unfreeze channel

sendbird-channel-settings__freeze

Leave channel

sendbird-channel-settings__leave-channel

How to use

Copy link

Use the following code to import ChannelSettings:

import { ChannelSettings } from "sendbird-uikit";

List of properties

Copy link
RequiredTypeDescription

channelUrl

string

The unique URL of the channel.

OptionalTypeDescription

onCloseClick

function

The prop to execute custom operations when the close button has been clicked. (Default: null)

onChannelModified

function

The prop to execute custom operations when a channel has been modified. (Default: null)

onBeforeUpdateChannel

function

The prop to execute custom operations before updating a channel.
- Function signature: fn(channelTitle, channelImage, Channel.data) => { return GroupChannelParams }

queries.applicationUserListQuery

instance

An ApplicationUserListQuery instance in ChannelSettings to retrieve users who are invited to a channel.

renderChannelProfile

ReactElement

Renders a customized channel preview section. For example, you can use this method to remove the Edit button in the Channel settings view.

disableUserProfile

boolean

Determines whether to display the profile preview section when clicking on the avatar. If set to true, the profile preview section is not shown. (Default: false)

renderUserProfile

ReactElement

Renders a customized user profile preview section when clicking on the avatar. The following are given as arguments:
- user: User, currentUserId: userId, close: function

The sample codes below show how to implement ChannelSettings with its properties.

onCloseClick&moreonBeforeUpdateChannelqueries.applicationUserListQuery
// onCloseClick & onChannelModified
import { ChannelSettings, SendBirdProvider } from "sendbird-uikit";
import "sendbird-uikit/dist/index.css";

const App = () => {
    <SendBirdProvider appId={appId} userId={userId}>
        <div style={{ height: '600px', textAlign: 'center' }}>
            <ChannelSettings channelUrl={channelUrl}
                onChannelModified-{channel => {...}}
                onCloseClick={() => { setShowSettings(false); }}
            />
        </div>
    </SendBirdProvider>
};