ReactJS is one of the most popular JavaScript frameworks used to power extremely dynamic web applications. By building a ReactJS component, we can develop powerful applications that seamlessly integrate Ant Media Server into React, making it more versatile and engaging.
Ant Media Server provides ultra-low latency WebRTC streaming capabilities that work seamlessly with modern JavaScript frameworks. While Ant Media offers an array of Software Development Kits (SDKs), for React applications, the JavaScript SDK is the ideal choice. In this guide, we will take you through a step-by-step process of harnessing the capabilities of the Ant Media JavaScript SDK in conjunction with React.
Our focus will be on publishing a WebRTC stream, covering all the essential setup steps such as importing dependencies, initializing the SDK, handling publishing events, and designing a user-friendly interface for the ReactJS component.
Let’s dive into the tutorial and get started with integrating Ant Media JavaScript SDK into your ReactJS project!
Table of Contents
Prerequisites
Step 1: Create a New ReactJS Project
Step 2: Install Dependencies
Step 3: Create the ReactJS Component
Understanding the code
Step 4: Update the App Component
Step 5: Run the Application
Play Component
Frequently Asked Questions
Conclusion
Prerequisites
ReactJS Component for WebRTC Live Streaming
Before getting started, make sure you have the following prerequisites:
Node.js installed on your machine
Basic knowledge of React and JavaScript
An Ant Media Server instance (Community or Enterprise Edition)
Full Code is Available on Github.
Step 1: Create a New ReactJS Project
Start by creating a new ReactJS project using Create React App. Open your terminal and run the following command:
1
npx create-react-app ant-media-streaming
This command will create a new directory named ant-media-streaming with a basic React project structure.
Step 2: Install Dependencies
Navigate to the project directory and install the required dependencies. Run the following command:
1
2
3
cd ant-media-streaming
npm i @antmedia/webrtc_adaptor
npm i bootstrap react-bootstrap
This command will install the Ant Media JS SDK, Bootstrap, and React Bootstrap packages. The @antmedia/webrtc_adaptor provides the core functionality for WebRTC streaming integration.
Step 3: Create the ReactJS Component
Inside the src directory, create a new file named PublishingComponent.js. This file will contain the code for the publishing component. Open PublishingComponent.js and add the following code:
Full Code is Available on Github.
import React, { useState, useEffect, useRef } from 'react';
import { Button, Container, Row, Col } from 'react-bootstrap';
import 'bootstrap/dist/css/bootstrap.min.css';
import { WebRTCAdaptor } from '@antmedia/webrtc_adaptor';
const PublishingComponent = () => {
const [publishing, setPublishing] = useState(false);
const [websocketConnected, setWebsocketConnected] = useState(false);
const [streamId, setStreamId] = useState('stream123');
const webRTCAdaptor = useRef(null);
var publishedStreamId = useRef(null);
const handlePublish = () => {
setPublishing(true);
webRTCAdaptor.current.publish(streamId);
publishedStreamId.current=streamId
};
const handleStopPublishing = () => {
setPublishing(false);
webRTCAdaptor.current.stop(publishedStreamId.current);
};
const handleStreamIdChange = (event) => {
setStreamId(event.target.value);
};
useEffect(() => {
if(webRTCAdaptor.current === undefined || webRTCAdaptor.current === null){
webRTCAdaptor.current = new WebRTCAdaptor({
websocket_url: 'wss://test.antmedia.io:/WebRTCAppEE/websocket',
mediaConstraints: {
video: true,
audio: true,
},
peerconnection_config: {
iceServers: [{ urls: 'stun:stun1.l.google.com:19302' }],
},
sdp_constraints: {
OfferToReceiveAudio: false,
OfferToReceiveVideo: false,
},
localVideoId: 'localVideo',
dataChannelEnabled: true,
callback: (info, obj) => {
if (info === 'initialized') {
setWebsocketConnected(true);
}
console.log(info, obj);
},
callbackError: function (error, message) {
console.log(error, message);
},
});
}
}, []);
return (
Publish Page
<Row className="mb-4">
<Col>
<video
id="localVideo"
controls
autoPlay
muted
style={{
width: '40vw',
height: '60vh',
maxWidth: '100%',
maxHeight: '100%',
}}
></video>
</Col>
</Row>
<Row className="justify-content-center">
<Row>
<div className="mb-3">
<input
className="form-control form-control-lg"
type="text"
defaultValue={streamId}
onChange={handleStreamIdChange}
/>
<label className="form-label" htmlFor="streamId">
Enter Stream Id
</label>
</div>
</Row>
<Col>
{!publishing ? (
<Button variant="primary" disabled={!websocketConnected} onClick={handlePublish}>
Start Publishing
</Button>
) : (
<Button variant="danger" onClick={handleStopPublishing}>
Stop Publishing
</Button>
)}
</Col>
</Row>
</Container>
);
};
export default PublishingComponent;
view rawsrc/PublishingComponent.js delivered with ❤ by emgithub
Understanding the code
Full Code is Available on Github.
Part 1: Importing Dependencies
import React, { useState, useEffect, useRef } from 'react';
import { Button, Container, Row, Col } from 'react-bootstrap';
import 'bootstrap/dist/css/bootstrap.min.css';
import { WebRTCAdaptor } from '@antmedia/webrtc_adaptor';
At the top of this ReactJS component, we import the necessary dependencies for our component. These include React, the useState, useEffect, and useRef hooks, Bootstrap components (Button, Container, Row, and Col), the Bootstrap CSS, and the WebRTCAdaptor from the Ant Media JS SDK.
We imported WebRTCAdaptor from the JS SDK which will act as an interface for us to publish and play streams from Ant Media Server
Part 2: Defining the Publishing Component
const PublishingComponent = () => {
const [publishing, setPublishing] = useState(false);
const [websocketConnected, setWebsocketConnected] = useState(false);
const [streamId, setStreamId] = useState('stream123');
const webRTCAdaptor = useRef(null);
var publishedStreamId = useRef(null);
// ... Rest of the component code ...
}
Here we define the PublishingComponent functional component. Inside this ReactJS component, we use the useState hook to create state variables: publishing, websocketConnected, and streamId. These variables will manage the publishing state, WebSocket connection status, and the entered stream ID, respectively.
We also create a webRTCAdaptor ref using the useRef hook. This ref will hold an instance of the WebRTCAdaptor class from the Ant Media JS SDK.
Part 3: Handling Publishing Events
const handlePublish = () => {
publishedStreamId.current=streamId
setPublishing(true);
webRTCAdaptor.current.stop(streamId);
};
const handleStopPublishing = () => {
setPublishing(false);
webRTCAdaptor.current.stop(publishedStreamId.current);
};
const handleStreamIdChange = (event) => {
setStreamId(event.target.value);
};
Next we define the event handler functions for publishing, stopping publishing, and stream ID change events. The handlePublish function sets the publishing state to true and calls the publish method of the webRTCAdaptor ref with the streamId.
The handleStopPublishing function sets the publishing state to false and calls the stop method of the webRTCAdaptor ref with the publishedStreamId.
The handleStreamIdChange function is triggered when the value of the stream ID input field changes. It updates the streamId state with the new value.
Part 4: Initializing WebRTC Adaptor
Note : Please Change The Ant Media IP in the WebRTCAdaptor Initialization
useEffect(() => {
webRTCAdaptor.current = new WebRTCAdaptor({
websocket_url: 'wss://AMS_IP:/WebRTCAppEE/websocket',
mediaConstraints: {
video: true,
audio: true,
},
peerconnection_config: {
iceServers: [{ urls: 'stun:stun1.l.google.com:19302' }],
},
sdp_constraints: {
OfferToReceiveAudio: false,
OfferToReceiveVideo: false,
},
localVideoId: 'localVideo',
callback: (info, obj) => {
if (info === 'initialized') {
setWebsocketConnected(true);
}
console.log(info, obj);
},
callbackError: function (error, message) {
console.log(error, message);
},
});
}, []);
To initialize the webRTCAdaptor, we’ll use the useEffect hook. The WebRTCAdaptor class handles all WebRTC connection management, including peer connections, media streams, and signaling through WebSocket connections.
The WebRTCAdaptor configuration requires several key parameters including websocket_url, mediaConstraints, and callback functions. For production deployments, you should implement proper stream security and token-based authentication.
Step 4: Update the App Component
Open the src/App.js file and replace its content with the following code:
In the above code, we import the PublishingComponent and render it inside the App component.
import PublishingComponent from './PublishingComponent';
import PlayingComponent from './PlayingComponent';
const App = () => {
return (
);
};
export default App;
view rawsrc/App.js delivered with ❤ by emgithub
Step 5: Run the Application
Save all the changes, and in your terminal, run the following command inside the project directory:
npm start
This command will start the development server, and you can view the application in your browser at http://localhost:3000. You should see the “Live Streaming” heading, a video element for displaying the local video stream, an input field for entering the stream ID, and a “Start Publishing” button.
Play Component
The ReactJS component built for playing the live stream is available here. The Play and Publish components are designed separately, but for the sake of simplicity they can be merged together if preferred. For advanced playback features, explore our complete playback documentation.
To use the player page, create a new component file called PlayingComponent.js and add the following code, which is available here.
Update the root ReactJS component to import the new play component as in the example below.
Run the npm start command in the directory.
import PlayingComponent from './PlayingComponent';
const App = () => {
return (
);
};
react
Player Page
Frequently Asked Questions
Can I use Ant Media JavaScript SDK with React 18?
Yes, the Ant Media JavaScript SDK works with React 18 and all React versions that support ES6+ syntax. The @antmedia/webrtc_adaptor package integrates seamlessly with modern React applications using hooks like useState and useRef.
What is the minimum latency achievable with WebRTC streaming in React?
WebRTC streaming through Ant Media Server achieves sub-second latency, typically between 0.5 to 1 second. This ultra-low latency is maintained regardless of whether you implement the streaming component in React, Vue, or vanilla JavaScript.
Do I need separate components for publishing and playing streams?
No, you can combine publishing and playing functionality in a single React component. However, separating them into distinct components improves code maintainability and allows independent reuse across your application.
How many concurrent streams can a React component handle?
A single React component can handle multiple concurrent streams limited only by browser capabilities and network bandwidth. Ant Media Server’s clustering feature supports scaling to thousands of concurrent viewers per stream.
Can I deploy React WebRTC components in production without modifications?
Yes, but you must replace the development WebSocket URL with your production Ant Media Server URL and implement proper error handling, connection recovery, and user permission management for camera/microphone access.
What browsers support WebRTC with React components?
All modern browsers support WebRTC: Chrome 74+, Firefox 66+, Safari 14+, Edge 79+, and Opera 62+. Mobile browsers including Chrome Mobile and Safari iOS also provide full WebRTC support for React applications.
Conclusion
You’ve now learned how to integrate the Ant Media JavaScript SDK into a ReactJS application to publish and play WebRTC streams with ease. By building reusable React components and leveraging WebRTC’s real-time capabilities, you can create fast, interactive, and highly engaging web experiences.
From setting up the SDK to handling publishing events and managing the UI, this guide gives you the foundation you need to start building real-time video features into your own React projects. Whether you’re working on live events, video conferencing tools, online classrooms, or interactive platforms, Ant Media Server provides the performance and scalability required for production use.
For more advanced implementations, explore our guides on building video conferencing apps, implementing adaptive bitrate streaming, and scaling your infrastructure to handle thousands of concurrent users.
Ready to take your streaming application to the next level? Check out our React Native SDK for building cross-platform mobile applications, or explore live WebRTC samples to see different use cases in action.
Now it’s your turn to experiment, customize, and innovate. Start your free trial with Ant Media Server, explore the SDK further, and bring immersive real-time streaming to your React applications.
Top comments (0)