How to Integrate Agora in React.js

prabhu govikarprabhu govikar
4 min read

"In this guide, we’ll walk through integrating Agora into a React.js application. By the end, you’ll know how to enable real-time video and audio communication on the frontend."

Create an Account in Agora

1.Go to Agora.io and click “Sign Up.”

2.After registering, verify your email and log in to the Agora console.

Create a Project in Agora Console

1.In the Agora Console, navigate to the Project management tab.

2.Click “Create” and give your project a name (e.g., Agora React Demo).

3.Set the authentication to “App ID + Token” (this ensures secure connections).

Understanding Channels and Tokens

Agora uses channels for real-time communication. A channel allows multiple users to join a virtual room for video/audio calls. Each user must authenticate their connection using a token. Here’s a quick breakdown:

  1. Channel :

    Think of it as a virtual room where people join to communicate.

    Users in the same channel can see and hear each other.

  2. Token

    A token is used to authenticate the user. It ensures that only authorized users can connect to a specific channel.

    For production: You should generate tokens dynamically on your server for security.

    For testing: Agora provides Temporary Tokens via the console.

Generate a Temporary Token

  1. In the Agora Console, open the project you created.

  2. Click “Generate Temp RTC Token” .

    click

  3. Enter a Channel Name (e.g., test-channel) and click Generate Token.

Setting up the React Application

  1. Create a React App

    First, open your terminal or command prompt and run the following command to create a new React application:

    npx create-react-app agora-react-app

  2. Install Agora SDK for React

    Agora provides the Agora RTC React library to help you manage real-time communication features.

    Install it using the following command:

    npm install agora-rtc-react

Initialize State Variables:

const [micOn, setMic] = useState(true);
const [cameraOn, setCamera] = useState(true);
const [speakerOn, setSpeaker] = useState(true);
const [activeConnection, setActiveConnection] = useState(true);

Use Agora Hooks for Tracks and Connection:

  1. useLocalMicrophoneTrack(): Manages the microphone track.

  2. useLocalCameraTrack(): Manages the camera track.

  3. useIsConnected(): Checks if the user is connected.

  4. useJoin(): Joins a specific channel using the App ID, channel name, and token.

     const { localMicrophoneTrack } = useLocalMicrophoneTrack(micOn);
     const { localCameraTrack } = useLocalCameraTrack(cameraOn);
     const isConnected = useIsConnected();
     useJoin({ appid: Agora_appId, channel: channelName, token }, activeConnection);
    

    Publish Local Tracks:

    This step ensures that the local microphone and camera tracks are published to the channel.

     usePublish([localMicrophoneTrack, localCameraTrack]);
    

    Display Remote Users:

     const remoteUsers = useRemoteUsers();
    

    Handle Call Disconnect:

     const disconnectCall = async () => {
       setActiveConnection(false);
       if (localMicrophoneTrack) {
         await localMicrophoneTrack.stop();
         await localMicrophoneTrack.close();
       }
       if (localCameraTrack) {
         await localCameraTrack.stop();
         await localCameraTrack.close();
       }
     };
    

    Toggle Speaker:

     const toggleSpeaker = () => {
       setSpeaker((prev) => !prev);
       if (localMicrophoneTrack) {
         localMicrophoneTrack.setVolume(speakerOn ? 0 : 100);
       }
     };
    

    App.js file looks like

     import React, { useState } from 'react';
     import {
       LocalUser,
       RemoteUser,
       useIsConnected,
       useJoin,
       useLocalMicrophoneTrack,
       useLocalCameraTrack,
       usePublish,
       useRemoteUsers,
     } from 'agora-rtc-react';
    
     const Agora_appId = 'YOUR_AGORA_APP_ID'; // Replace with your App ID
     const channelName = 'test-channel'; // Example channel name
     const token = 'YOUR_TEMP_TOKEN'; // Replace with your temporary token
    
     export default function Video() {
       const [activeConnection, setActiveConnection] = useState(true);
       const [micOn, setMic] = useState(true);
       const [cameraOn, setCamera] = useState(true);
       const [speakerOn, setSpeaker] = useState(true);
    
       // Agora hooks to manage audio and video tracks
       const { localMicrophoneTrack } = useLocalMicrophoneTrack(micOn);
       const { localCameraTrack } = useLocalCameraTrack(cameraOn);
       const isConnected = useIsConnected();
    
       // Publish local tracks (microphone & camera)
       usePublish([localMicrophoneTrack, localCameraTrack]);
    
       // Fetch remote users connected to the same channel
       const remoteUsers = useRemoteUsers();
       console.log('Remote Users:', remoteUsers);
    
       // Join the channel using Agora's useJoin hook
       useJoin({ appid: Agora_appId, channel: channelName, token }, activeConnection);
    
       // Function to disconnect the call and clean up resources
       const disconnectCall = async () => {
         setActiveConnection(false);
         if (localMicrophoneTrack) {
           await localMicrophoneTrack.stop();
           await localMicrophoneTrack.close();
         }
         if (localCameraTrack) {
           await localCameraTrack.stop();
           await localCameraTrack.close();
         }
       };
    
       // Toggle speaker functionality
       const toggleSpeaker = () => {
         setSpeaker((prev) => !prev);
         if (localMicrophoneTrack) {
           localMicrophoneTrack.setVolume(speakerOn ? 0 : 100);
         }
       };
    
       return (
         <div className="video-call-container">
           {/* Local Video Section */}
           <div className="video-container">
             {localCameraTrack && (
               <LocalUser
                 audioTrack={localMicrophoneTrack}
                 videoTrack={localCameraTrack}
                 cameraOn={cameraOn}
                 micOn={micOn}
                 className="localUser"
               />
             )}
           </div>
    
           {/* Call Controls */}
           <div className="controls-toolbar">
             <button onClick={() => setMic((prev) => !prev)}>
               <img
                 src={micOn ? require('./assets/mic.png') : require('./assets/microphone.png')}
                 alt="Mic Toggle"
               />
             </button>
             <button onClick={disconnectCall}>
               <img src={require('./assets/disconnectcall.png')} alt="End Call" />
             </button>
             <button onClick={toggleSpeaker}>
               <img
                 src={speakerOn ? require('./assets/volume.png') : require('./assets/volume-down.png')}
                 alt="Speaker Toggle"
               />
             </button>
           </div>
    
           {/* Remote Users Section */}
           <div id="remoteUsers">
             {remoteUsers.map((user) => (
               <div key={user.uid} className="remote-user-video">
                 <RemoteUser user={user} className="remoteUser" />
               </div>
             ))}
           </div>
         </div>
       );
     }
    

    Add Your Own Icons and Update Image Paths

    Place your own images in the /public or /src/assets/ folder (depending on your project structure).

    With this code, you’ve successfully integrated Agora in your React.js application. This component allows users to:

    1. Join a video call with microphone and camera.

    2. See remote participants.

    3. Mute/unmute the microphone and toggle the speaker.

    4. Disconnect the call and clean up resources.

You can further enhance this by adding styles and error handling for a smoother user experience.

20
Subscribe to my newsletter

Read articles from prabhu govikar directly inside your inbox. Subscribe to the newsletter, and don't miss out.

Written by

prabhu govikar
prabhu govikar