How to Integrate Chat Feature in React JS Video Call App
Tags: javascript, react
Published: 2024-04-16 10:44:06

---
title: How to Integrate Chat Feature in React JS Video Call App
published: true
date: 2024-04-15 12:18:18 UTC
tags: javascript, react
canonical_url: https://www.videosdk.live/blog/integrate-chat-feature-in-react-js
---

## 📌 Introduction
 ![How to Integrate Chat Feature in React JS Video Call App?](https://assets.videosdk.live/static-assets/ghost/2024/04/Chat-React.png)

Integrating a chat feature into a [React JS video call app](https://www.videosdk.live/blog/react-js-video-calling) enhances communication and collaboration. By seamlessly blending real-time video and text chat, users can discuss, share links, and exchange information concurrently, enriching the interactive experience. Utilizing React JS ensures smooth integration, leveraging its component-based architecture for streamlined development. Implementing features like message threading, emoji support, and real-time updates further enrich the chat experience, fostering engagement and productivity.

Benefits of Chat Feature:

1. **Enhanced Communication:** Seamlessly integrate text chat with video calls for richer communication experiences.
2. **Increased Collaboration:** Users can share links, files, and information in real-time, fostering collaboration.
3. **Improved Productivity:** Instant messaging alongside video calls accelerates decision-making and task completion.
4. **Flexible Interaction:** Users can choose between video or text communication based on preferences or situational needs.
5. **Better User Experience:** React JS ensures smooth integration and UI updates, enhancing the overall user experience.

Build your modern ReactJS video-calling app with a chat feature and VideoSDK - unlock enhanced communication and collaboration possibilities.

## 🚀 Getting Started with VideoSDK

To take advantage of the chat functionality, we must use the capabilities that the VideoSDK offers. Before diving into the implementation steps, let's ensure you complete the necessary prerequisites.

### Create a VideoSDK Account

Go to your [VideoSDK dashboard](https://www.videosdk.live/signup?utm_source=organicseo&utm_medium=devto&utm_campaign=chat_feature_react_js) and sign up if you don't have an account. This account gives you access to the required Video SDK token, which acts as an authentication key that allows your application to interact with VideoSDK functionality.

### Generate your Auth Token

Visit your VideoSDK dashboard and navigate to the "API Key" section to generate your auth token. This token is crucial in authorizing your application to use VideoSDK features.

For a more visual understanding of the account creation and token generation process, consider referring to the [provided tutorial](https://docs.videosdk.live/android/guide/video-and-audio-calling-api-sdk/authentication-and-token#1-generating-token-from-dashboard).

### Prerequisites and Setup

Before proceeding, ensure that your development environment meets the following requirements:

- VideoSDK Developer Account (Not having one?, follow **[VideoSDK Dashboard](https://app.videosdk.live/)**)
- Basic understanding of React.
- **[React VideoSDK](https://www.npmjs.com/package/@videosdk.live/react-sdk)**
- Make sure Node and NPM are installed on your device.
- Basic understanding of Hooks (useState, useRef, useEffect)
- React Context API (optional)

Follow the steps to create the environment necessary to add video calls to your app. You can also find the code sample for [Quickstart here](https://github.com/videosdk-live/quickstart/tree/main/react-rtc).[​](https://docs.videosdk.live/react/guide/video-and-audio-calling-api-sdk/quick-start#create-new-react-app)

**Create a new React App using the below command.**

```
$ npx create-react-app videosdk-rtc-react-app
```

## 🛠️ Install VideoSDK[​](https://docs.videosdk.live/react/guide/video-and-audio-calling-api-sdk/quick-start#install-videosdk)

It is necessary to set up VideoSDK within your project before going into the details of integrating the Screen Share feature. Installing VideoSDK using NPM or Yarn will depend on the needs of your project.

- For NPM

```
$ npm install "@videosdk.live/react-sdk"

//For the Participants Video
$ npm install "react-player"
```

- For Yarn

```
$ yarn add "@videosdk.live/react-sdk"

//For the Participants Video
$ yarn add "react-player"
```

You are going to use functional components to leverage React's reusable component architecture. There will be components for users, videos and controls (mic, camera, leave) over the video.

<!--kg-card-begin: markdown-->
### App Architecture
<!--kg-card-end: markdown-->

The App will contain a `MeetingView` component which includes a `ParticipantView` component which will render the participant's name, video, audio, etc. It will also have a `Controls` component that will allow the user to perform operations like leave and toggle media.

![How to Integrate Chat Feature in React JS Video Call App?](https://docs.videosdk.live/assets/images/react-quick-start-fafbfbc2ed2d7cbfd4c5ee2e36296f9e.png)

You will be working on the following files:

- API.js: Responsible for handling API calls such as generating unique meetingId and token
- App.js: Responsible for rendering `MeetingView` and joining the meeting.

## 🎥 Essential Steps to Implement Video Calling Functionality

To add video capability to your React application, you must first complete a sequence of prerequisites.

### Step 1: Get started with API.js[​](https://docs.videosdk.live/react/guide/video-and-audio-calling-api-sdk/quick-start#step-1-get-started-with-apijs)

Before moving on, you must create an API request to generate a unique meetingId. You will need an authentication token, which you can create either through the [videosdk-rtc-api-server-examples](https://github.com/videosdk-live/videosdk-rtc-api-server-examples) or directly from the [VideoSDK Dashboard](https://app.videosdk.live/api-keys) for developers.

```
//This is the Auth token, you will use it to generate a meeting and connect to it
export const authToken = "<Generated-from-dashbaord>";
// API call to create a meeting
export const createMeeting = async ({ token }) => {
  const res = await fetch(`https://api.videosdk.live/v2/rooms`, {
    method: "POST",
    headers: {
      authorization: `${authToken}`,
      "Content-Type": "application/json",
    },
    body: JSON.stringify({}),
  });
  //Destructuring the roomId from the response
  const { roomId } = await res.json();
  return roomId;
};
```

### Step 2: Wireframe App.js with all the components[​](https://docs.videosdk.live/react/guide/video-and-audio-calling-api-sdk/quick-start#step-2-wireframe-appjs-with-all-the-components)

To build up a wireframe of App.js, you need to use VideoSDK Hooks and Context Providers. VideoSDK provides MeetingProvider, MeetingConsumer, useMeeting, and useParticipant hooks.

First, you need to understand the **Context Provider** and Consumer. Context is primarily used when some data needs to be accessible by many components at different nesting levels.

- **MeetingProvider** : This is the Context Provider. It accepts value `config` and `token` as props. The Provider component accepts a value prop to be passed to consuming components that are descendants of this Provider. One Provider can be connected to many consumers. Providers can be nested to override values deeper within the tree.
- **MeetingConsumer** : This is the Context Consumer. All consumers that are descendants of a Provider will re-render whenever the Provider’s value prop changes.
- **useMeeting** : This is the meeting hook API. It includes all the information related to meetings such as join/leave, enable/disable the mic or webcam, etc.
- **useParticipant** : This is the participant hook API. It is responsible for handling all the events and props related to one particular participant such as **name** , **webcamStream** , **micStream** , etc.

The Meeting Context provides a way to listen for any changes that occur when a participant joins the meeting or makes modifications to their microphone, camera, and other settings.

Begin by making a few changes to the code in the **App.js** file.

```
import "./App.css";
import React, { useEffect, useMemo, useRef, useState } from "react";
import {
  MeetingProvider,
  MeetingConsumer,
  useMeeting,
  useParticipant,
} from "@videosdk.live/react-sdk";
import { authToken, createMeeting } from "./API";
import ReactPlayer from "react-player";

function JoinScreen({ getMeetingAndToken }) {
  return null;
}

function ParticipantView(props) {
  return null;
}

function Controls(props) {
  return null;
}

function MeetingView(props) {
  return null;
}

function ChatView() {
  return null;
}

function App() {
  const [meetingId, setMeetingId] = useState(null);

  //Getting the meeting id by calling the api we just wrote
  const getMeetingAndToken = async (id) => {
    const meetingId =
      id == null ? await createMeeting({ token: authToken }) : id;
    setMeetingId(meetingId);
  };

  //This will set Meeting Id to null when meeting is left or ended
  const onMeetingLeave = () => {
    setMeetingId(null);
  };

  return authToken && meetingId ? (
    <MeetingProvider
      config={{
        meetingId,
        micEnabled: true,
        webcamEnabled: true,
        name: "C.V. Raman",
      }}
      token={authToken}
    >
      <MeetingView meetingId={meetingId} onMeetingLeave={onMeetingLeave} />
    </MeetingProvider>
  ) : (
    <JoinScreen getMeetingAndToken={getMeetingAndToken} />
  );
}

export default App;
```

_App.js_

### Step 3: Implement Join Screen[​](https://docs.videosdk.live/react/guide/video-and-audio-calling-api-sdk/quick-start#step-3-implement-join-screen)

The join screen will serve as a medium to either schedule a new meeting or join an existing one.

```
function JoinScreen({ getMeetingAndToken }) {
  const [meetingId, setMeetingId] = useState(null);
  const onClick = async () => {
    await getMeetingAndToken(meetingId);
  };
  return (
    <div>
      <input
        type="text"
        placeholder="Enter Meeting Id"
        onChange={(e) => {
          setMeetingId(e.target.value);
        }}
      />
      <button onClick={onClick}>Join</button>
      {" or "}
      <button onClick={onClick}>Create Meeting</button>
    </div>
  );
}
```
<!--kg-card-begin: markdown-->
#### Output
<!--kg-card-end: markdown-->

![How to Integrate Chat Feature in React JS Video Call App?](https://docs.videosdk.live/assets/images/react-join-screen-06fb57cf0d9e3bcc1e7da9fc032298c3.jpeg)

### Step 4: Implement MeetingView and Controls[​](https://docs.videosdk.live/react/guide/video-and-audio-calling-api-sdk/quick-start#step-4-implement-meetingview-and-controls)

The next step is to create `MeetingView` and `Controls` components to manage features such as join, leave, mute, and unmute.

```
function MeetingView(props) {
  const [joined, setJoined] = useState(null);
  //Get the method which will be used to join the meeting.
  //We will also get the participants list to display all participants
  const { join, participants } = useMeeting({
    //callback for when meeting is joined successfully
    onMeetingJoined: () => {
      setJoined("JOINED");
    },
    //callback for when meeting is left
    onMeetingLeft: () => {
      props.onMeetingLeave();
    },
  });
  const joinMeeting = () => {
    setJoined("JOINING");
    join();
  };

  return (
    <div className="container">
      <h3>Meeting Id: {props.meetingId}</h3>
      {joined && joined == "JOINED" ? (
        <div>
          <Controls />
          //For rendering all the participants in the meeting
          {[...participants.keys()].map((participantId) => (
            <ParticipantView
              participantId={participantId}
              key={participantId}
            />
          ))}
          <ChatView />
        </div>
      ) : joined && joined == "JOINING" ? (
        <p>Joining the meeting...</p>
      ) : (
        <button onClick={joinMeeting}>Join</button>
      )}
    </div>
  );
}

function Controls() {
  const { leave, toggleMic, toggleWebcam } = useMeeting();
  return (
    <div>
      <button onClick={() => leave()}>Leave</button>
      <button onClick={() => toggleMic()}>toggleMic</button>
      <button onClick={() => toggleWebcam()}>toggleWebcam</button>
    </div>
  );
}
```

_Control Component_
<!--kg-card-begin: markdown-->
#### Output of Controls Component
<!--kg-card-end: markdown-->

![How to Integrate Chat Feature in React JS Video Call App?](https://docs.videosdk.live/assets/images/react-container-controls-2cebdfdfd1371b010b773cb6fb9c7ae8.jpeg)

### Step 5: Implement Participant View[​](https://docs.videosdk.live/react/guide/video-and-audio-calling-api-sdk/quick-start#step-5-implement-participant-view)

Before implementing the participant view, you need to understand a couple of concepts.

<!--kg-card-begin: markdown-->
#### 5.1 Forwarding Ref for mic and camera
<!--kg-card-end: markdown-->

The `useRef` hook is responsible for referencing the audio and video components. It will be used to play and stop the audio and video of the participant.

```
const webcamRef = useRef(null);
const micRef = useRef(null);
```

_Forwarding Ref for mic and camera_
<!--kg-card-begin: markdown-->
#### 5.2 useParticipant Hook
<!--kg-card-end: markdown-->

The `useParticipant` hook is responsible for handling all the properties and events of one particular participant who joined the meeting. It will take participantId as an argument.

```
const { webcamStream, micStream, webcamOn, micOn } = useParticipant(
  props.participantId
);
```
<!--kg-card-begin: markdown-->
#### 5.3 MediaStream API
<!--kg-card-end: markdown-->

The MediaStream API is beneficial for adding a MediaTrack to the audio/video tag, enabling the playback of audio or video.

```
const webcamRef = useRef(null);
const mediaStream = new MediaStream();
mediaStream.addTrack(webcamStream.track);

webcamRef.current.srcObject = mediaStream;
webcamRef.current
  .play()
  .catch((error) => console.error("videoElem.current.play() failed", error));
```
<!--kg-card-begin: markdown-->
#### 5.4 Implement `ParticipantView`​
<!--kg-card-end: markdown-->

Now you can use both of the hooks and the API to create `ParticipantView`

```
function ParticipantView(props) {
  const micRef = useRef(null);
  const { webcamStream, micStream, webcamOn, micOn, isLocal, displayName } =
    useParticipant(props.participantId);

  const videoStream = useMemo(() => {
    if (webcamOn && webcamStream) {
      const mediaStream = new MediaStream();
      mediaStream.addTrack(webcamStream.track);
      return mediaStream;
    }
  }, [webcamStream, webcamOn]);

  useEffect(() => {
    if (micRef.current) {
      if (micOn && micStream) {
        const mediaStream = new MediaStream();
        mediaStream.addTrack(micStream.track);

        micRef.current.srcObject = mediaStream;
        micRef.current
          .play()
          .catch((error) =>
            console.error("videoElem.current.play() failed", error)
          );
      } else {
        micRef.current.srcObject = null;
      }
    }
  }, [micStream, micOn]);

  return (
    <div>
      <p>
        Participant: {displayName} | Webcam: {webcamOn ? "ON" : "OFF"} | Mic:{" "}
        {micOn ? "ON" : "OFF"}
      </p>
      <audio ref={micRef} autoPlay playsInline muted={isLocal} />
      {webcamOn && (
        <ReactPlayer
          //
          playsinline // extremely crucial prop
          pip={false}
          light={false}
          controls={false}
          muted={true}
          playing={true}
          //
          url={videoStream}
          //
          height={"300px"}
          width={"300px"}
          onError={(err) => {
            console.log(err, "participant video error");
          }}
        />
      )}
    </div>
  );
}
```

## Integrate Chat Feature

For communication or any kind of messaging between participants, VideoSDK provides the `usePubSub` hook, which utilizes the Publish-Subscribe mechanism. It can be employed to develop a wide variety of functionalities. For example, participants could use it to send chat messages to each other, share files or other media, or even trigger actions like muting or unmuting audio or video.

This guide focuses on using PubSub to implement Chat functionality. If you are not familiar with the PubSub mechanism and `usePubSub` hook, you can [follow this guide](https://docs.videosdk.live/react/guide/video-and-audio-calling-api-sdk/collaboration-in-meeting/pubsub).

### Implementing Group Chat

- The initial step in setting up a group chat involves selecting a topic to which all participants will publish and subscribe, facilitating the exchange of messages. In the following example, `CHAT` is used as the topic. Next, obtain the `publish()` method and the `messages` array from the `usePubSub`hook.

```
// importing usePubSub hook from react-sdk
import { usePubSub } from "@videosdk.live/react-sdk";

function ChatView() {
  // destructure publish method from usePubSub hook
  const { publish, messages } = usePubSub("CHAT");

  return <>...</>;
}
```

- Next create a message input and a send button to publish the messages.

```
function ChatView() {
  // destructure publish method from usePubSub hook
  const { publish, messages } = usePubSub("CHAT");

  // State to store the user typed message
  const [message, setMessage] = useState("");

  const handleSendMessage = () => {
    // Sending the Message using the publish method
    publish(message, { persist: true });
    // Clearing the message input
    setMessage("");
  };

  return (
    <>
      <input
        value={message}
        onChange={(e) => {
          setMessage(e.target.value);
        }}
      />
      <button onClick={handleSendMessage}>Send Message</button>
    </>
  );
}
```

- The final step in the group chat is to display the messages sent by others. For this use the `messages` array and display all the messages.

```
function ChatView() {
  // destructure publish method from usePubSub hook
  const { publish, messages } = usePubSub("CHAT");

  const [message, setMessage] = useState("");

  const handleSendMessage = () => {
    ...
  };

  return (
    <>
      <div>
      <p>Messages: </p>
      {messages.map((message) => {
        return (
          <p>
            {messsage.senderName} says {message.message}
          </p>
        );
      })}
      </div>
      <input
        value={message}
        onChange={(e) => {
          setMessage(e.target.value);
        }}
      />
      <button onClick={handleSendMessage}>Send Message</button>
    </>
  );
}
```

### Implement Private Chat[​](https://docs.videosdk.live/react/guide/video-and-audio-calling-api-sdk/collaboration-in-meeting/chat-using-pubsub#private-chat)

In the above example, to convert the chat into a private one between two participants, set the `sendOnly` property.

```
function ChatView() {
  // destructure publish method from usePubSub hook
  const { publish, messages } = usePubSub("CHAT");

  // State to store the user typed message
  const [message, setMessage] = useState("");

  const handleSendMessage = () => {
    // Sending the Message using the publish method
    // Pass the participantId of the participant to whom you want to send the message.
    publish(message, { persist: true , sendOnly: ['XYZ'] });
    // Clearing the message input
    setMessage("");
  };

  //...
}
```

### Display the Latest Message Notification[​](https://docs.videosdk.live/react/guide/video-and-audio-calling-api-sdk/collaboration-in-meeting/chat-using-pubsub#display-latest-message-notificaiton)

To show the notification to the user when a new message arrives, the following code snippet has to be followed.

```
function ChatView() {
  // destructure publish method from usePubSub hook
  const { publish, messages } = usePubSub("CHAT", {
    onMessageReceived: (message)=>{
      window.alert(message.senderName + "says" + message.message);
    }
  });
  const [message, setMessage] = useState("");
  const handleSendMessage = () => {
    ...
  };
  return <>...</>;
}
```

### Downloading Chat Messages[​](https://docs.videosdk.live/react/guide/video-and-audio-calling-api-sdk/collaboration-in-meeting/chat-using-pubsub#downloading-chat-messages)

All the messages from PubSub published  `persist : true` can be downloaded as a `.csv` file. This file will be accessible in the VideoSDK dashboard and through the [Sessions API](https://docs.videosdk.live/api-reference/realtime-communication/fetch-session-using-sessionid).

## 🎯 Conclusion

By following these steps, you'll have successfully integrated a chat feature into your React.js video call app using VideoSDK. Integrating a chat feature into your React JS video calls offers numerous benefits, including enhanced communication, collaboration, and engagement among participants. By incorporating this feature, you not only improve the overall user experience but also empower users to communicate more effectively during video calls. Whether for business meetings, remote collaboration, or virtual events, the addition of a chat feature enhances the functionality and utility of your video conferencing platform.

To unlock the full potential of VideoSDK and create easy-to-use video experiences, developers are encouraged to **[Sign up with VideoSDK](https://www.videosdk.live/signup?utm_source=organicseo&utm_medium=devto&utm_campaign=chat_feature_react_js)** today and Get **10000 minutes free** to take the video app to the next level!