> ## Documentation Index
> Fetch the complete documentation index at: https://docs.quickblox.com/llms.txt
> Use this file to discover all available pages before exploring further.

# 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](https://admin.quickblox.com/signup). 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 UIKit. 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

```JavaScript JavaScript theme={null}
npm install quickblox
```

### Install QuickBlox UIKit

```JavaScript JavaScript theme={null}
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.

```JavaScript JavaScript theme={null}
`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);
```

<Warning>
  **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](/sdks/js-setup#install-quickblox-sdk-into-your-app)
</Warning>

### 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](/sdks/js-authentication).
In our example we show how to authenticate user with login and password.

```JavaScript JavaScript theme={null}
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

### Step 1. Creating a React Project with TypeScript and Webpack

In this section, we will guide you through creating a new React project using TypeScript and Webpack without using `create-react-app`. This manual setup gives you complete control over the build process, which is useful when integrating advanced SDKs and UIKits.

**Initializing the Project**

1. Open your terminal and create a new project directory:

```bash theme={null}
mkdir react-chat-ui-kit-init-sample
cd react-chat-ui-kit-init-sample
npm init -y
```

**Installing Dependencies**

Install the required libraries and tools:

```bash theme={null}
# Application dependencies
npm install react react-dom

# TypeScript and types
npm install --save-dev typescript @types/react @types/react-dom @types/node

# Webpack and its core plugins
npm install --save-dev webpack webpack-cli webpack-dev-server html-webpack-plugin copy-webpack-plugin

# Loaders for styles and scripts
npm install --save-dev ts-loader style-loader css-loader sass-loader sass

# Babel support
npm install --save-dev babel-loader @babel/core @babel/preset-env @babel/preset-react @babel/preset-typescript

# SVG loader
npm install --save-dev @svgr/webpack
```

**Creating Configuration Files**

Create a `tsconfig.json` in the root folder:

```json theme={null}
{
  "compilerOptions": {
    "target": "ESNext",
    "lib": ["DOM", "DOM.Iterable", "ESNext"],
    "allowJs": true,
    "skipLibCheck": true,
    "esModuleInterop": true,
    "allowSyntheticDefaultImports": true,
    "strict": true,
    "forceConsistentCasingInFileNames": true,
    "module": "ESNext",
    "moduleResolution": "Node",
    "resolveJsonModule": true,
    "isolatedModules": true,
    "jsx": "react-jsx",
    "noEmit": true
  },
  "include": ["src"]
}
```

Also create a `webpack.config.js` file (see example in the QuickBlox repository for a complete working configuration
[webpack.config.js](https://github.com/QuickBlox/quickblox-javascript-sdk/blob/gh-pages/samples/react-chat-ui-kit-init-sample/webpack.config.js)).

**Creating the Project Structure**

Manually create the following folder and file structure:

```
public/
  index.html
src/
  App.tsx
  App.css
  index.tsx
  QBconfig.ts
  logo.svg
webpack.config.js
tsconfig.json
package.json
```

**Example of `public/index.html`**

```html theme={null}
<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="UTF-8" />
    <title>React UIKit Example</title>
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
  </head>
  <body>
    <div id="root"></div>
  </body>
</html>
```

**Creating the Entry Point**

In `src/index.tsx`, add the following code:

```tsx theme={null}
import React from 'react';
import ReactDOM from 'react-dom/client';
import App from './App';
import './index.css';

const root = ReactDOM.createRoot(document.getElementById('root') as HTMLElement);
root.render(<App />);
```

**Adding NPM Scripts**

In your `package.json`, update the scripts section to include:

```json theme={null}
"scripts": {
  "start": "webpack serve --mode development",
  "build": "webpack --mode production"
}
```

**Running the Project**

Start the development server:

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

Then open your browser at [https://localhost:3000](https://localhost:3000) to view the running application.

You now have a working React + TypeScript + Webpack project ready to integrate the QuickBlox UIKit. Continue to the next section to add the required configuration and SDK logic.

### 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:

```Powershell Powershell theme={null}
 npm install quickblox --save
```

3. Then, execute the following command to install the `quickblox-react-ui-kit` package:

```Powershell Powershell theme={null}
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>
  Note: use // @ts-ignor

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

```JavaScript JavaScript theme={null}
// @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 UIKit 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:

```JavaScript JavaScript theme={null}
  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.

<Warning>
  Note: if the SDK was initialized using a session token, use the same sessionToken in the UIKit.

  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](/sdks/js-setup#install-quickblox-sdk-into-your-app)
</Warning>

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

```Typescript TypeScript theme={null}
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:

```TypeScript TypeScript theme={null}
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 }}
       qbConfig={{ ...QBConfig }}
       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.
* qbConfig - the configuration file structure contains settings such as session duration for the React Kit, keys for interacting with AI features, and so on.
* 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 UIKit 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.

```TypeScript TypeScript theme={null}
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:

```TypeScript TypeScript theme={null}
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.

```TypeScript TypeScript theme={null}
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 }}
            qbConfig={{ ...QBConfig }}
            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:

```Powershell Powershell theme={null}
npm start
```

<iframe width="560" height="315" className="centered-video" src="https://www.youtube.com/embed/FYQkVbi21to?si=" title="YouTube video player" frameborder="0" allow="accelerometer; autoplay; clipboard-write; encrypted-media; gyroscope; picture-in-picture; web-share" referrerpolicy="strict-origin-when-cross-origin" allowfullscreen />

Also you can find the project from video here: [React Chat UIKit init example](https://github.com/QuickBlox/quickblox-javascript-sdk/tree/gh-pages/samples/react-chat-ui-kit-init-sample).

For more guidance please See helpful tutorial:

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

  Use this link [ React Chat UIKit init example.](https://github.com/QuickBlox/quickblox-javascript-sdk/tree/gh-pages/samples/react-chat-ui-kit-init-sample)
</Note>

<Tip>
  Quick start for using our React UIKit see, [React UIKit Demonstration Sample](https://github.com/QuickBlox/quickblox-javascript-sdk/tree/gh-pages/samples/react-chat-ui-kit-demo-app).

  This sample implements authorization functionality and provides an example of color theme customization. The sample code is available by this [link](https://github.com/QuickBlox/quickblox-javascript-sdk/tree/gh-pages/samples/react-chat-ui-kit-demo-app). 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](https://quickblox.com/blog/how-to-create-a-react-chat-application-with-quickblox-uikit/).
</Tip>

In the short video (approximately 12 minutes long) below, we will guide you through the process of creating a React chat application using the QuickBlox UIKit v0.3.1.

<iframe width="560" height="315" className="centered-video" src="https://www.youtube.com/embed/0QFqNjhP-wM?si=WgvDnfkyO5zjamYZ" title="YouTube video player" frameborder="0" allow="accelerometer; autoplay; clipboard-write; encrypted-media; gyroscope; picture-in-picture; web-share" referrerpolicy="strict-origin-when-cross-origin" allowfullscreen />
