October 6, 2020

Add Video to Your React Chat App

Umar Elbelel

Introduction

Leveraging on the CometChat UI KIT to handle our logics, we will be adding a video call functionality to our react application. As technology keeps growing the need for real time data transfer is becoming much; from chat, voice calls to video calls all use the same technology. In this tutorial, we would take you through the steps required to add a video chat functionality to your react project.


When completed we should have our video functionality added to our react application similar to the one below.

Prerequisite

Before we dive into the main functionality, there are some things you will be needing to get started

  1. Setting up a CometChat account and creating an App
  2. React application setup

Once you have that then you are ready to start

Installing CometChat SDK

After setting up your react application, next is to introduce CometChat Pro SDK. This is required for our application to appropriately collaborate with CometChat.


Run the below command to install the SDK:

{% c-line %}npm install @cometchat-pro/chat@2.1.0 --save{% c-line-end %}


After installing our dependency, we need to instate it and to do that we need to incorporate it at the initial stage of our application. Open the "index.js" file  and add the following content to it.


{% c-block language="javascript" %}
var appID = "APP_ID";
var region = "REGION";
var appSetting = new CometChat.AppSettingsBuilder().subscribePresenceForAllUsers().setRegion(region).build();
CometChat.init(appID, appSetting).then(
 () => {
   console.log("Initialization completed successfully");
 },
 error => {
   console.log("Initialization failed with error:", error);
 }
);
{% c-block-end %}

Don’t forget to replace the APP_ID and REGION placeholders with your credentials.


Setting up the CometChat UI KIT

To setup the CometChat UI KIT we need to first clone it to our project directory. To achieve that run the command below:


git clone https://github.com/cometchat-pro/javascript-react-chat-ui-kit.git


Once this is done, copy the CometChat folder to your source folder. Next is for us to install all the needed dependency for the CometChat UI KIT, to do that, copy the dependency below to your “package.json” file.


{% c-block language="javascript" %}
"node-sass": "^4.12.1",
"classnames": "^2.2.6",
"balloon-css": "^1.2.0",
"emoji-mart": "^3.0.0",
"react-html-parser": "^2.0.2",
"twemoji": "^13.0.1"
{% c-block-end %}


To install these packages run the following command:

{% c-line %}npm install{% c-line-end %}

After setting up and installing all needed dependency for the CometChat UI Kit, we can now be able to make use of the components to add video interface and logics to our application.


Creating Register/Login Component

Before we can access our video call component, we need to be authenticated. To do that navigate to your source folder and create a folder called components (this is where all our components will be).

Once you have done that, the next is to create a login component “login.js”; and paste the code below:


{% c-block language="javascript" %}
import React  from 'react';
import {Container, Row, Col, Form, Button} from 'react-bootstrap'
import Image from '../background.png'
import {API_KEY} from '../constant/constant'
import  {CometChat} from '@cometchat-pro/chat'
import { useHistory } from 'react-router'
export const Login = () => {
   const [username, setUsername] = React.useState('')
   const [isSubmitting, setIsSubmitting] = React.useState(false)
   const history = useHistory()
const login = async (username) => {
       const UID = username
var user = new CometChat.User(UID);
user.setName(username);
   if(username){
     CometChat.createUser(user, API_KEY).then(
       user => {
           console.log("user created", user);
           CometChat.login(UID,API_KEY).then(
               data => {
                   history.push('/video')
               },
               error => {
                 console.log("Login failed with exception:", { error });    
               }
             );
       },error => {
           CometChat.login(UID,API_KEY).then(
               data => {
                 history.push('/video')
               },
               error => {
                 console.log("Login failed with exception:", { error });    
               }
             );
       }
   )
   }else{
     history.push('/video')
   }
}
   const formsubmit = async (e) =>{
       e.preventDefault()
       setIsSubmitting(true)
       const data = await login(username)
       if(data){
       setIsSubmitting(false)
       setUsername('')
       }
   }
   return(          
     <Container>
          <Row>
               <Col md={8} className='top-margin'>
               <center >
                   <img src={Image} className='mt-5' alt='background'/>
               </center>
               </Col>
               <Col md={4} className='margin-top'>
               <h5><strong>WELCOME TO COMETCHAT VIDEO CALL</strong></h5>
               <Row>
                   <div className='ml-3' onClick={()=>{ setIsSubmitting(true);  login('superhero1')}}>
                       <img src='https://data-us.cometchat.io/assets/images/avatars/ironman.png' height='50px' width='50px' alt='superher1'/>
                           <p>superhero1</p>
                           </div>
                           <div className='ml-3' onClick={()=>{ setIsSubmitting(true);login('superhero2')}}>
                       <img src='https://data-us.cometchat.io/assets/images/avatars/captainamerica.png' height='50px' width='50px' alt='superher2'/>
                           <p>superhero2</p>
                           </div>
                           <div className='ml-3' onClick={()=>{setIsSubmitting(true); login('superhero3')}}>
                       <img src='https://data-us.cometchat.io/assets/images/avatars/spiderman.png' height='50px' width='50px' alt='superher3' />
                           <p>superhero3</p>
                           </div>
                   </Row>
                   <Form onSubmit={formsubmit} >
                   <Form.Control type='text' placeholder='Enter or click the username above' className='mt-2' onChange={(e)=> setUsername(e.target.value)} />
                     <Button type='submit' variant="primary" className='bt-width mt-4' disabled={isSubmitting}>
                         Login {isSubmitting ? (<i className="fa fa-spinner fa-spin"></i>) : null}
                         </Button>
                   </Form>
               </Col>
           </Row>
          </Container>
)
   }
{% c-block-end %}


The login component handles our authentication, this allows us to log in to CometChat using the default users provided (superhero1, superhero2, superhero3) or by registering a new user through which an input field is provided. Upon submission of the input or click of one of the default users we triggered the login().


The login() handle our request by first checking if the user is set, subsequently creating the user using the CometChat.createUser().


If the user is already registered, we trigger the CometChat.login() which authenticated our user.

Hence, we redirect the user to the video component.


The image below shows the login interface.


For our styling, we use the bootstrap CDN included in our “index.html” file.


Creating Video Component

Begin by navigating to our src/components and create our “video.js” file; open the file and paste the code below


{% c-block language="javascript" %}
import React from 'react'
import {CometChatUserListScreen} from "../CometChat";
import  {CometChat} from '@cometchat-pro/chat'
import { useHistory } from 'react-router'
export const  Video = () => {
 const history = useHistory()
 const logout = async () => {
   CometChat.logout().then(user=>{
       history.push('/')
   });  
 }
React.useEffect(()=>{
 const refresh = async ()=> {
  await CometChat.getLoggedinUser()
 }
 refresh()
},[])
   return(
     <div>
       <button className= "btn btn-width btn-medium btn-primary" onClick={logout}>
logout</button>
         <CometChatUserListScreen/>
     </div>
   )
}
{% c-block-end %}

On the mount of this component, we initialize the refresh() which gets our logged in user, we then import the CometChatUserListScreen component from the CometChat SDK we cloned earlier.

This component will list all users and also handle all the logics of accepting, rejecting, and also the video call interface.

The image below shows the user list, which allows us to select a user.


To initialize a video call tab on the video icon on the top right-hand corner, this will allow the other user to either accept or reject the call. the image below will describe the process.


Testing Our Application

To test our application, run the following command to start it up:

{% c-line %}npm run start{% c-line-end %}

Navigate to your browser and open http://localhost:3000 to access the application


Conclusion

Thanks to CometChat UI KIT we were able to add a video call functionality with little or no difficulty. The CometChat UI KIT gives us all we need from functionalities, user interface, API calls and everything necessary. No need to call APIs to fetch the call history or users.


Hope you found this tutorial helpful. Don’t forget to check the official documentation of CometChat to explore further and add more features to your react application. The complete source code to this tutorial is available on GitHub.