Rendering a single track

To demonstrate how to build a UI to render a single video stream, imagine this scenario:

We have a LiveKit Room with three Participants who are constantly streaming a camera feed into the room. In our example, the Participants are not human, but webcams streaming from "Berlin", "New York" and "Tokyo". For unknown reasons, we only want to see the stream from "Tokyo".

We start by creating a new React component and get all the camera tracks with useTracks([Track.Source.Camera]). In the returned array of TrackReferences we look for the Tokyo stream. Since we know that all webcam participants are named after their cities, we look for the tokyo participant.

import { useTracks } from '@livekit/components-react';
import { Track } from 'livekit-client';
function CityVideoRenderer() {
const trackRefs = useTracks([Track.Source.Camera]);
const tokyoCamTrackRef = trackRefs.find((trackRef) => trackRef.participant.name === 'tokyo');
return <>TODO</>;
}

Now that we have found the correct stream, we can move on to building the UI to display it. We can do this by importing the VideoTrack component and passing it the track reference. If the Tokyo track reference is not found, we will display a UI to indicate this instead.

import { useTracks, VideoTrack } from '@livekit/components-react';
import { Track } from 'livekit-client';
function CityVideoRenderer() {
const trackRefs = useTracks([Track.Source.Camera]);
const tokyoCamTrackRef = trackRefs.find((trackRef) => trackRef.participant.name === 'tokyo');
return (
<>
{tokyoCamTrackRef ? <VideoTrack trackRef={tokyoCamTrackRef} /> : <div>Tokyo is offline</div>}
</>
);
}

With our UI in place, we need to provide useTracks with the proper context to return the tracks of a LiveKit Room. We do this by nesting everything inside the <LiveKitRoom> component.

import { LiveKitRoom, useTracks, VideoTrack } from '@livekit/components-react';
import { Track } from 'livekit-client';
function CityVideoRenderer() {
const trackRefs = useTracks([Track.Source.Camera]);
const tokyoCamTrackRef = trackRefs.find((trackRef) => trackRef.participant.name === 'tokyo');
return (
<>
{tokyoCamTrackRef ? <VideoTrack trackRef={tokyoCamTrackRef} /> : <div>Tokyo is offline</div>}
</>
);
}
function MyPage() {
return (
<LiveKitRoom>
<CityVideoRenderer />
</LiveKitRoom>
);
}