A Comprehensive Guide to Implementing Agora Video SDK in a React Project

Agora Video SDK provides a robust solution for real-time video and audio communication. Integrating it with a React application can enable features like video calling, conferencing, and live streaming. This guide will walk you through implementing Agora Video SDK in a React project, with step-by-step instructions and code examples.

Prerequisites

Before starting, ensure you have the following:

  • Node.js and npm/yarn are installed on your system.
  • A React project set up. You can create one using create-react-app or Vite.
  • An Agora account to obtain an App ID. Sign up at Agora.io.

Related read: Upgrading Your React Application to Next.js: A Step-by-Step Guide

Step 1: Set Up a React Project

If you don’t have a React project already, create one:

npx create-react-app agora-video-app
cd agora-video-app

Step 2: Install the Agora SDK

Agora provides an npm package for their Web SDK. Install it in your project:

npm install agora-rtc-sdk-ng

Step 3: Configure Your Agora App ID

Log in to your Agora console, create a project, and note the App ID. This ID will initialize the Agora Video SDK.

Create a .env file in the root of your project and add your App ID:

REACT_APP_AGORA_APP_ID=your-app-id-here

Step 4: Create a Video Call Component

Now, let’s create a VideoCall component to handle the video call logic.

VideoCall.js :

import React, { useEffect, useRef, useState } from 'react';
import { createClient, createMicrophoneAndCameraTracks } from 'agora-rtc-sdk-ng';
const appId = process.env.REACT_APP_AGORA_APP_ID; // App ID from .env
const client = createClient({ mode: "rtc", codec: "vp8" });
const VideoCall = ({ channelName, token }) => {
  const [users, setUsers] = useState([]);
  const [start, setStart] = useState(false);
  const [tracks, setTracks] = useState(null);
  const remoteVideoRefs = useRef({});
useEffect(() => {
 const init = async () => {
  const [localAudioTrack, localVideoTrack] = await createMicrophoneAndCameraTracks();

  client.on("user-published", async (user, mediaType) => {
  await client.subscribe(user, mediaType);
  if (mediaType === "video") {
    setUsers((prevUsers) => [...prevUsers, user]);
  }
 })
 client.on("user-unpublished", (user) => {
    setUsers((prevUsers) => prevUsers.filter((u) => u.uid !== user.uid));
 });
 await client.join(appId, channelName, token, null);
 await client.publish([localAudioTrack, localVideoTrack]);
 setTracks([localAudioTrack, localVideoTrack]);
 setStart(true);
};
init();
return () => {
  client.leave();
  tracks?.forEach((track) => track.close());
};
}, [channelName, token]);
return (
<div>
  <div id="local-stream">
    {tracks && <video autoPlay playsInline ref={(ref) => ref && tracks[1].play(ref)} />}
  </div>
<div id="remote-streams">
 {users.map((user) => (
  <video key={user.uid}
  autoPlay
  playsInline
  ref={(ref) => {
     if (ref) {
       user.videoTrack?.play(ref);
     }
    }}
   />
  ))}
 </div>
</div>
);
};
export default VideoCall;

Start Integrating Agora Video SDK in Your React Project Today and Unlock Seamless Communication Features!

Explanation

Client Initialization: We create a client with createClient and specify the mode and codec.

  1. Joining a Channel: The client.join method connects to the specified channel with the token.
  2. Publishing Tracks: Microphone and camera tracks are created and published.
  3. User Management: Listens for user-published and user-unpublished events to manage remote streams.
  4. Rendering Streams: The local-stream and remote-streams divs display the video streams.

Step 5: Implement the Component in Your App

Use the VideoCall component in your application.

App.js:

import React from 'react';
import VideoCall from './VideoCall';
function App() {
  const channelName = "testChannel";
  const token = null; // Replace with a token if your project requires one.
  return (
    <div className="App">
  <h1>Agora Video Call</h1>
    <VideoCall channelName={channelName} token={token} />
    </div>
  );
}
export default App;

Step 6: Test the Application

Run the application: npm start

Open your application in multiple browser tabs or devices to test the functionality provided by the Agora Video SDK.

Step 7: Enhance the Application

Add Mute and Leave Controls:

You can add buttons to mute/unmute the microphone or leave the call:

<button onClick={() => tracks[0].setEnabled(false)}>Mute</button>
<button onClick={() => tracks[0].setEnabled(true)}>Unmute</button>
<button onClick={() => client.leave()}>Leave</button>

Style the Application

Use CSS to style the video streams and layout.

#local-stream, #remote-streams video {
 width: 300px;
 height: 200px;
 margin: 10px;
 border: 1px solid black;
}
coma

Conclusion

You can easily build powerful video communication features with the Agora Video SDK and React. This guide provides a foundational implementation, which you can expand to create a fully-featured video-conferencing application. Whether aiming for basic video calls or complex features, the Agora Video SDK ensures a seamless development experience.

Keep Reading

Keep Reading

  • Service
  • Career
  • Let's create something together!

  • We’re looking for the best. Are you in?