Chat UIKit React v3
Chat UIKit React
Chat UIKit
React
Version 3

Integrate UIKit to an existing app

Copy link

This tutorial walks you through the process of integrating UIKit into your existing application.


Prerequisites

Copy link
  • Sendbird UIKit library. If you don't have it yet, follow the steps in Send your first message to install the library.
  • Sendbird account and Sendbird application to use the UIKit library. If you don't have an account, you can create one here.
  • At least two users should be created in the Sendbird dashboard to test the chat functionality. You can create users on Sendbird Dashboard.

How to customize

Copy link

Step 1 Clone the starter code

Copy link

In most cases, you will already have an existing application that you want to add chat functionality to. In this tutorial, we will build a simple delivery app first to demonstrate how to integrate UIKit into an existing app. This app requires a chat feature so that users can communicate with their delivery person.

To get started, clone the starter code from the GitHub repository. You can find the code in the integrate-with-existing-app/before folder.

The app basically has two screens as follows:

  • Login Screen: A simple form to enter the user ID.
  • Order Status Screen: A screen to show the order details and the status.

Step 2 Integrate UIKit

Copy link

From this step we will:

  • Add a chat button to the OrderStatus component.
  • Create a channel and open the chat screen when the user clicks the chat button.

Step 2-1 Import the required components

Copy link
import { useSendbirdStateContext } from '@sendbird/uikit-react';
import { GroupChannel } from '@sendbird/uikit-react/GroupChannel';
import SendbirdProvider from '@sendbird/uikit-react/SendbirdProvider';

import '@sendbird/uikit-react/dist/index.css';

Step 2-2 Define a custom hook to create a channel

Copy link

We will define a custom hook to create a channel and open the chat screen.

const useCreateChannel = (userId: string, deliveryPersonId: string, onCreateChannel: (url: string) => void) => {
  // To use the context, the component should be wrapped in the SendbirdProvider.
  const { stores } = useSendbirdStateContext(); // Access the Sendbird state context
  const sdk = stores.sdkStore.sdk; // Get the Sendbird SDK instance

  return async () => {
    // Ensure that SDK is initialized
    if (!sdk || !sdk.groupChannel) {
      console.log('SDK not initialized');
      return;
    }

    // Use the SDK to create a new group channel
    const params = {
      invitedUserIds: [userId, deliveryPersonId],
      isDistinct: true, // Reuse the channel if it already exists
    };

    // In production, you should handle the error using try-catch
    const channel = await sdk.groupChannel.createChannel(params);
    onCreateChannel(channel.url);
  };
};

In the code snippet above:

  • Using the sdk instance, you can create a channel, send a message, and more. For more information, please refer to the API reference page.
  • The SendbirdProvider is a context provider that provides the Sendbird SDK instance to its children. It should be placed at the top of the component tree to provide the SDK instance to all the children components.

Step 2-3 Add the chat button

Copy link

Let's create a chat button component to create a channel and open the chat screen.

type ChatButtonProps = { userId: string; deliveryPersonId: string; onCreateChannel: (url: string) => void };
const ChatButton = ({userId, deliveryPersonId, onCreateChannel}: ChatButtonProps) => {
  const onStartChat = useCreateChannel(userId, deliveryPersonId, onCreateChannel);
  return <button onClick={onStartChat}>{'Chat with Delivery Person'}</button>;
};

We will add the chat button to the children of OrderStatus.

const App = () => {
  // ... Other states
  
  const [showChat, setShowChat] = useState(false); // State to toggle the visibility of the chat
  const [channelUrl, setChannelUrl] = useState(''); // State to store the channel URL
  
  const handleCreateChannel = (url: string) => {
    setChannelUrl(url);
    setShowChat(true);
  };

  // ... Previous codes
  
  const renderApp = () => {
    return (
      <div className="app-container">
        <OrderStatus orderDetails={orderDetails}>
          {showChat ? (
            <button onClick={() => setShowChat(false)}>{'Close'}</button>
          ) : (
            <ChatButton userId={userId} deliveryPersonId={orderDetails.deliveryPersonId} onCreateChannel={handleCreateChannel} />
          )}
        </OrderStatus>
      </div>
    );
  };

  return <div className="App">{showLogin ? renderLoginForm() : renderApp()}</div>;
};

Step 2-4 Add the SendbirdProvider and the GroupChannel component

Copy link

Finally, we will add the SendbirdProvider and the GroupChannel component to the main app.

Be sure to replace:

  • YOUR_APP_ID with your actual Sendbird application ID.
  • DELIVERY_PERSON_ID with the actual user ID.
const App = () => {
  // ... Previous codes
  const renderApp = () => {
    // YOUR_APP_ID can be found in the dashboard. link:
    // For details about the app, please refer this link:
    const APP_ID = 'YOUR_APP_ID';
    return (
      <div className="app-container">
        <SendbirdProvider appId={APP_ID} userId={userId}>
          <OrderStatus orderDetails={orderDetails}>
            {showChat ? (
              <button onClick={() => setShowChat(false)}>{'Close'}</button>
            ) : (
              <ChatButton userId={userId} deliveryPersonId={orderDetails.deliveryPersonId} onCreateChannel={handleCreateChannel} />
            )}
          </OrderStatus>
          {showChat && <GroupChannel channelUrl={channelUrl} />}
        </SendbirdProvider>
      </div>
    );
  };

  return <div className="App">{showLogin ? renderLoginForm() : renderApp()}</div>;
}

Step 3 Run the app

Copy link

Now, you can run the app and test the chat functionality.

Full code

Copy link

You can refer the full code from the GitHub repository.