Send your first message

The QuickBlox UIKit for React comprises a collection of pre-assembled UI components that enable effortless creation of an in-app chat equipped with all the necessary messaging functionalities. Our development kit encompasses light and dark themes, colors, and various other features. These components can be personalized to fashion an engaging messaging interface that reflects your brand's distinct identity.

The QuickBlox UIKit fully supports both private and group dialogs. To initiate the process of sending a message from the ground up using Java or Kotlin, please refer to the instructions provided in the guide below.

Requirements

The minimum requirements for QuickBlox UIKit for React are:

  • JS QuickBlox SDK v2.15.5
  • React v.18.0
  • TypeScript v.4.9.3

Before you begin

Register a new account following this link. Type in your email and password to sign in. You can also sign in with your Google or Github accounts.
Create the app clicking New app button.
Configure the app. Type in the information about your organization into corresponding fields and click Add button.
Go to Dashboard => YOUR_APP => Overview section and copy your Application ID, Authorization Key, Authorization Secret, and Account Key .

Helicopter overview

Before you start coding, let's provide a brief introduction and explain the steps for developers. Firstly, you should install our JS SDK and UI Kit. Secondly, you need to create a session, log in using the credentials of an already registered user, and connect to the chat.

Install QuickBlox SDK

npm install quickblox

Install QuickBlox UIKit

npm install quickblox-react-ui-kit

Init QuickBlox SDK

To init QuickBlox SDK you need to pass Application ID, Authorization Key, Authorization Secret, and Account Key to the init() method.

var APPLICATION_ID = 41;
var AUTH_KEY = "lkjdueksu7392kj";
var AUTH_SECRET = "iiohfdija792hj";
var ACCOUNT_KEY = "sdjfnksnlk2bk1k34kb";
var CONFIG = { debug: true };

QB.init(APPLICATION_ID, AUTH_KEY, AUTH_SECRET, ACCOUNT_KEY, CONFIG);

❗️

Security

It's not recommended to keep your authKey and authSecret inside an application in production mode, instead of this, the best approach will be to store them on your backend. Instead you can initialize QuickBlox SDK without Authorization Key and Secret

Authentication

Before sending your first message you need to authenticate users in the QuickBlox system. You can read more about different ways of authentication by this link.
In our example we show how to authenticate user with login and password.

import * as QB from "quickblox/quickblox";
import { QuickBloxUIKitProvider } from 'quickblox-ui-kit-react';

QB.createSession(function(error, result) {
  var params = { login: "garry", password: "garry5santos" };

  QB.login(params, function(error, result) {
    if(error){
    } else {
      //Connect to chat and navigate User to the UIKit
  });
});

Get started

The entire process consists of several steps:

  • Creating a React Project with TypeScript
  • Adding Dependencies to a React Project
  • Adding QBconfig.ts File to Your React Application
  • Perhaps updating the project structure according to your needs
  • Configure QuickBloxUIKitProvider

In the short video (approximately 12 minutes long) below, we demonstrate all the steps, and in the following text sections, we delve into each step in more detail. Also you can find the project from video here: React Chat UI Kit init example.

Step1. Creating a React Project with TypeScript

In this section, we will provide a step-by-step guide on how to create a React project using TypeScript. TypeScript is a statically typed superset of JavaScript that provides enhanced development capabilities.

Installing Required Tools

  1. Ensure that Node.js is installed on your computer. You can download it from the official Node.js website (https://nodejs.org).
  2. Open your command prompt or terminal and check the Node.js version by running the command:
    node -v
    
  3. Make sure you have the npm package manager installed by running the command:
    npm -v
    

Creating a New Project

  1. Open your command prompt or terminal and navigate to the directory where you want to create your new project.
    Run the following command to create a new React project with TypeScript:
npx create-react-app my-app --template typescript
  1. Wait for the project creation process to complete. Once finished, you will see a success message indicating that your project has been created.

Removing Default Project Content

Before proceeding with your own development, it's recommended to remove the default content that comes with the newly created React project.

  • Delete or modify the files in the src directory according to your project requirements. You can also remove the default styles in the App.css file and the default logo in the logo.svg file.

By cleaning up the default project content, you can start with a clean slate and build your React application from scratch.

Running the Project

  1. Navigate to your project directory using the command cd my-app (replace my-app with your project name).
  2. Start the project by running the command:
    npm start
    
  3. Open your browser and go to http://localhost:3000. You will see your React application up and running.
    You have now successfully created a React project using TypeScript and removed the default project content. You can start developing your application, adding components and functionality based on the capabilities provided by React and TypeScript.

Step2. Adding Dependencies to a React Project

To successfully integrate QuickBlox functionality into your React project, you need to add two main dependencies: quickblox and quickblox-react-ui-kit. By following the documentation, you can easily add these packages to your project.

Installing Dependencies

  1. Open your command prompt or terminal and navigate to the root folder of your React project.
  2. Run the following command to install the quickblox package:
     npm install quickblox --save
    
  3. Then, execute the following command to install the quickblox-react-ui-kit package:
    npm install quickblox-react-ui-kit --save
    

Importing Dependencies in the Project

  1. Open the file where you want to use QuickBlox functionality, such as App.tsx
  2. Add the following lines at the beginning of the file to import the dependencies:

📘

Note: use // @ts-ignor

We are using // @ts-ignor in TypeScript because QuickBlox SDK doesn't share types.


// @ts-ignore
import * as QB from "quickblox/quickblox";  
import 'quickblox-react-ui-kit'

Using QuickBlox in the Project

Now that the dependencies are successfully added to your project, you can utilize QuickBlox functionality within the relevant components and modules of your application. Refer to the quickblox and quickblox-react-ui-kit documentation for more detailed information on the available features and components you can use.

Step 3. Adding QBconfig.ts File to Your React Application

To ensure proper configuration and functionality of the QuickBlox UIKit in your React application, it is essential to add a QBconfig.ts file to the src folder. This file allows you to define the necessary parameters for the QuickBlox UIKit.
The QBconfig.ts file contains various configuration settings that determine how the QuickBlox UIKit interacts with the QuickBlox JavaScript SDK and the backend services. These settings include:

  1. appId: This parameter represents the unique identifier assigned to your QuickBlox application. It helps establish a connection between the frontend and backend components.
  2. authKey and authSecret: These parameters are used for authentication purposes. They ensure secure communication between your application and the QuickBlox backend.
  3. accountKey: This parameter identifies your QuickBlox account and provides access to the associated services.
  4. apiEndpoint and chatEndpoint: These parameters define the API and chat endpoints provided by QuickBlox. They specify the URLs to which the QuickBlox UIKit will send requests for various functionalities.

To illustrate, here is an example of a QBconfig.ts file:

export const QBConfig = {
    credentials: {
        appId: YOUR_APP_ID_FROM_ADMIN_PANEL,
        accountKey: 'YOUR_ACCOUNT_KEY_FROM_ADMIN_PANEL',
        authKey: 'YOUR_AUTH_KEY_FROM_ADMIN_PANEL',
        authSecret: 'YOUR_AUTH_SECRET_FROM_ADMIN_PANEL',
        sessionToken: '',
    },
    appConfig: {
        chatProtocol: {
            Active: 2,
        },
        debug: false,
        endpoints: {
            apiEndpoint: 'https://api.quickblox.com',
            chatEndpoint: 'chat.quickblox.com',
        },
        on: {
            async sessionExpired(handleResponse: any, retry: any) {
                console.log(`Test sessionExpired… ${handleResponse} ${retry}`);
            }
        },
        streamManagement: {
            Enable: true,
        },
    },
};

In this example, make sure to replace the placeholder values (YOUR_APP_ID_FROM_ADMIN_PANEL, YOUR_ACCOUNT_KEY_FROM_ADMIN_PANEL, YOUR_AUTH_KEY_FROM_ADMIN_PANEL, YOUR_AUTH_SECRET_FROM_ADMIN_PANEL) with the actual values obtained from your QuickBlox application.
By adding the QBconfig.ts file to your React application, you ensure that the QuickBlox UIKit is properly configured and can interact seamlessly with the QuickBlox backend services.

🚧

Note: if the SDK was initialized using a session token, use the same sessionToken in the UI Kit.

If you initialize your SDK using a session token, you need to not only fill the sessionToken field in QBConfig but also fill other properties in the same way as when using the initWithAppId method. See the link initialize QuickBlox SDK without Authorization Key and Secret

Now we can add dependecies in our code. (Open your App.tsx and add that lines.)

import * as QB from "quickblox/quickblox";
import 'quickblox-react-ui-kit';
import { QBConfig } from './QBconfig'; // this line is new

Step 4. Updating the project structure according to your needs

In order to enhance the organization and maintainability of your project, it is recommended to make changes to the structure of the App.tsx in the src folder.
You need to add a constant called "currentUser" inside the App() function in the App.tsx file, which describes your user registered in the admin panel, and configure the QuickBloxUIKitProvider. Additionally, import the necessary entities from quickblox-react-ui-kit.
As a result, you should have the code below:

import React from 'react';
import * as QB from "quickblox/quickblox";
import {
   LoginData,
   QuickBloxUIKitProvider,
   qbDataContext,
   RemoteDataSource,
   useQBConnection, QuickBloxUIKitDesktopLayout,
} from 'quickblox-react-ui-kit';


function App() { 

const currentUser: LoginData = {
   		userName: 'YOUR_REGISTRED_USER_NAME',
   		password: 'YOUR_REGISTRED_USER_PASSWORD',
};

	return (
   <QuickBloxUIKitProvider
       maxFileSize={100 * 1000000}
       accountData={{ ...QBConfig.credentials }}
       loginData={{
           login: currentUser.login,
           password: currentUser.password,
       }}
   >
       <div className="App">
 		<QuickBloxUIKitDesktopLayout />
       </div>
   </QuickBloxUIKitProvider>
);

}

export default App;

QuickBloxUIKitProvider can accept up to three parameters:

  • maxFileSize - controls the maximum size of uploaded files.
  • accountData - information about the application's account data.
  • loginData - information about the logged-in user.

Let's add the QuickBlox UIKit chat layer - QuickBloxUIKitDesktopLayout - to the markup of the main component of the application.

If we do not specify a sessionToken in accountData, it means that the login and session start process occurs within our application. In this case, it is necessary to perform the following fifth step in our instruction.
However, if the session start and application login process is already performed in another application, such as on a server, and we already have a ready sessionToken, then we can skip the next step.

Step 5. Configure QuickBloxUIKitProvider

To configure QuickBloxUIKitProvider and use QuickBloxUIKit in your application, follow these steps:
Initialize DataContext:

  1. To work with QuickBlox, it is necessary to initialize the UI Kit react DataContext. It contains important data and settings for using QuickBloxSDK. The DataContext connects various components of the application and provides them access to shared data.

    const qbUIKitContext: QBDataContextType = React.useContext(qbDataContext);
    
      const [isUserAuthorized, setUserAuthorized] = React.useState(false);
      const [isSDKInitialized, setSDKInitialized] = React.useState(false);
    
      const prepareSDK = async (): Promise<void> => {
        // check if we have installed SDK
        if ((window as any).QB === undefined) {
          if (QB !== undefined) {
            (window as any).QB = QB;
          } else {
            let QBLib = require('quickblox/quickblox.min');
            (window as any).QB = QBLib;
          }
        }
    
        const APPLICATION_ID = QBConfig.credentials.appId;
        const AUTH_KEY = QBConfig.credentials.authKey;
        const AUTH_SECRET = QBConfig.credentials.authSecret;
        const ACCOUNT_KEY = QBConfig.credentials.accountKey;
        const CONFIG = QBConfig.appConfig;
    
        QB.init(APPLICATION_ID, AUTH_KEY, AUTH_SECRET, ACCOUNT_KEY, CONFIG);
    
      };
    
  2. We need to add user authentication, so to do this, we will introduce two states and use the useEffect hook:

    const [authorized, setAuthorized] = React.useState(false);
    const [initedSDK, setInitedSDK] = React.useState(false);
    
    ......
    
     useEffect(() => {
        if (!isSDKInitialized) {
          prepareSDK().then(result => {
    
            QB.createSession(currentUser, async function (errorCreateSession: any, session: any) {
              if (errorCreateSession) {
                console.log('Create User Session has error:', JSON.stringify(errorCreateSession));
              } else {
                const userId: number = session.user_id;
                const password: string = session.token;
                const paramsConnect = { userId, password };
    
                QB.chat.connect(paramsConnect, async function (errorConnect: any, resultConnect: any) {
                  if (errorConnect) {
                    console.log('Can not connect to chat server: ', errorConnect);
                  } else {
                    const authData: AuthorizationData = {
                      userId: userId,
                      password: password,
                      userName: currentUser.login,
                      sessionToken: session.token
                    };
                    await qbUIKitContext.authorize(authData);
                    setSDKInitialized(true);
                    setUserAuthorized(true);
                  }
                });
              }
            });
          }).catch(
              e => {
                console.log('init SDK has error: ', e)
              });
        }
      }, []);
      
      ......
    

After implementing all the steps, your App.tsx file should look like this. You can compare it this your code or copy it instead of.

import React, { useEffect } from 'react';

// @ts-ignore
import * as QB from "quickblox/quickblox";
import {
  QuickBloxUIKitProvider,
  qbDataContext,
  QuickBloxUIKitDesktopLayout, LoginData, AuthorizationData, QBDataContextType,
} from 'quickblox-react-ui-kit';
import { QBConfig } from './QBconfig';
import './App.css';

function App() {

  const currentUser: LoginData = {
    login: '',
    password: '',
  };

  const qbUIKitContext: QBDataContextType = React.useContext(qbDataContext);

  const [isUserAuthorized, setUserAuthorized] = React.useState(false);
  const [isSDKInitialized, setSDKInitialized] = React.useState(false);

  const prepareSDK = async (): Promise<void> => {
    // check if we have installed SDK
    if ((window as any).QB === undefined) {
      if (QB !== undefined) {
        (window as any).QB = QB;
      } else {
        let QBLib = require('quickblox/quickblox.min');
        (window as any).QB = QBLib;
      }
    }

    const APPLICATION_ID = QBConfig.credentials.appId;
    const AUTH_KEY = QBConfig.credentials.authKey;
    const AUTH_SECRET = QBConfig.credentials.authSecret;
    const ACCOUNT_KEY = QBConfig.credentials.accountKey;
    const CONFIG = QBConfig.appConfig;

    QB.init(APPLICATION_ID, AUTH_KEY, AUTH_SECRET, ACCOUNT_KEY, CONFIG);

  };

  useEffect(() => {
    if (!isSDKInitialized) {
      prepareSDK().then(result => {

        QB.createSession(currentUser, async function (errorCreateSession: any, session: any) {
          if (errorCreateSession) {
            console.log('Create User Session has error:', JSON.stringify(errorCreateSession));
          } else {
            const userId: number = session.user_id;
            const password: string = session.token;
            const paramsConnect = { userId, password };

            QB.chat.connect(paramsConnect, async function (errorConnect: any, resultConnect: any) {
              if (errorConnect) {
                console.log('Can not connect to chat server: ', errorConnect);
              } else {
                const authData: AuthorizationData = {
                  userId: userId,
                  password: password,
                  userName: currentUser.login,
                  sessionToken: session.token
                };
                await qbUIKitContext.authorize(authData);
                setSDKInitialized(true);
                setUserAuthorized(true);
              }
            });
          }
        });
      }).catch(
          e => {
            console.log('init SDK has error: ', e)
          });
    }
  }, []);

  return (
      <div>
        <QuickBloxUIKitProvider
            maxFileSize={100 * 1000000}
            accountData={{ ...QBConfig.credentials }}
            loginData={{
              login: currentUser.login,
              password: currentUser.password,
            }}
        >
          <div className="App">
            {
              // React states indicating the ability to render UI
              isSDKInitialized && isUserAuthorized
                  ?
                  <QuickBloxUIKitDesktopLayout />
                  :
                  <div>wait while SDK is initializing...</div>
            }
          </div>
        </QuickBloxUIKitProvider>
      </div>
  );
}

export default App;

You should run the application using the command:

npm start

For more guidance please see our helpful tutorial:

📘

Note: you can find the code from this project on our repository.

Use this link React Chat UI Kit init example.

👍

Quick start for using our React UI Kit see, React UI Kit Demonstration Sample.

This sample implements authorization functionality and provides an example of color theme customization. The sample code is available by this link. How to set up and run a sample, see the article in our blog How to Create a React Chat Application in Just a Few Steps.