In LiveKit Components loops are used for two things:
- Loop over participant tracks like camera, screen share or microphone tracks.
- Loop over participants in a room.
Both loops have in common that they only accept one or no child. If no child is provided the default component is used. If a child is provided, it is used as a template for every item in the loop.
Track Loop
The TrackLoop
component loops over tracks. It is for example a easy way to loop over all participant camera and screen share tracks. TrackLoop
creates a TrackContext
for each track that you can use to e.g. render the track. The TrackLoop
accepts zero or one child component as a template.
const cameraTracks = useTracks([Track.Source.Camera]);<TrackLoop tracks={cameraTracks} ><TrackContext.Consumer>{(track) => track && <VideoTrack {...track}/>}</TrackContext.Consumer><TrackLoop />
Info how is this different from the
ParticipantLoop
? One participant can have more than one track. E.g. it is not uncommon to loop over all camera as well as scree share tracks.
Participant Loop
The ParticipantLoop
component loops over an array of participants to create a ParticipantContext
for every participant. This component takes exactly one child component as a template. By providing your own template as a child you have full control over the look and feel of your participant representations.
const participants = useParticipants();<ParticipantLoop participants={participants}><ParticipantName /><ParticipantLoop />
For more details take a look at the API pages: ParticipantLoop and useParticipants
Filter Loops
In order to loop over only a subset of the tracks, you will need to filter the tracks before passing them as a property to the TrackLoop
. Use the standard Array.filter() function to do so.
const tracks = useTracks([{ source:Track.Source.Camera, withPlaceholder: true },{ source: Track.Source.ScreenShare, withPlaceholder: false },])const screenShareTracks = tracks.filter((track) => track.publication.source === Track.Source.ScreenShare,);// Loop only over screen share tracks.<TrackLoop tracks={screenShareTracks}><ParticipantTile /><TrackLoop />