npm package discovery and stats viewer.

Discover Tips

  • General search

    [free text search, go nuts!]

  • Package details

    pkg:[package-name]

  • User packages

    @[username]

Sponsor

Optimize Toolset

I’ve always been into building performant and accessible sites, but lately I’ve been taking it extremely seriously. So much so that I’ve been building a tool to help me optimize and monitor the sites that I build to make sure that I’m making an attempt to offer the best experience to those who visit them. If you’re into performant, accessible and SEO friendly sites, you might like it too! You can check it out at Optimize Toolset.

About

Hi, 👋, I’m Ryan Hefner  and I built this site for me, and you! The goal of this site was to provide an easy way for me to check the stats on my npm packages, both for prioritizing issues and updates, and to give me a little kick in the pants to keep up on stuff.

As I was building it, I realized that I was actually using the tool to build the tool, and figured I might as well put this out there and hopefully others will find it to be a fast and useful way to search and browse npm packages as I have.

If you’re interested in other things I’m working on, follow me on Twitter or check out the open source projects I’ve been publishing on GitHub.

I am also working on a Twitter bot for this site to tweet the most popular, newest, random packages from npm. Please follow that account now and it will start sending out packages soon–ish.

Open Software & Tools

This site wouldn’t be possible without the immense generosity and tireless efforts from the people who make contributions to the world and share their work via open source initiatives. Thank you 🙏

© 2026 – Pkg Stats / Ryan Hefner

mediasfu-reactnative

v2.3.5

Published

MediaSFU Prebuilt React Native SDK

Readme

License: MIT Twitter GitHub Website YouTube Community

Built with MediaSFU React Native TypeScript NPM

MediaSFU React Native SDK provides a comprehensive solution for building real-time communication applications. Part of the MediaSFU ecosystem with cross-platform support for iOS and Android environments, seamlessly integrating video conferencing, live streaming, and interactive media features into your mobile applications.


🚨 BREAKING: AI Phone Agents at $0.10 per 1,000 minutes

📞 Call our live AI demos right now:

  • 🇺🇸 +1 (785) 369-1724 - Mixed Support Demo
  • 🇬🇧 +44 7445 146575 - AI Conversation Demo
  • 🇨🇦 +1 (587) 407-1990 - Technical Support Demo
  • 🇨🇦 +1 (647) 558-6650 - Friendly AI Chat Demo

Traditional providers charge $0.05 per minute. We charge $0.10 per 1,000 minutes. That's 500x cheaper.

Deploy AI phone agents in 30 minutes
Works with ANY SIP provider (Twilio, Telnyx, Zadarma, etc.)
Seamless AI-to-human handoffs
Real-time call analytics & transcription

📖 Complete SIP/PSTN Documentation →


Quick Reference: Component Props & UI Overrides

New: UI override parity now extends across Webinar and Chat layouts, unifying customization for every MediaSFU interface.

Every primary MediaSFU UI export—MediasfuGeneric, MediasfuBroadcast, MediasfuConference, MediasfuWebinar, and MediasfuChat—now ships with a consistent prop surface and a powerful uiOverrides map, so you can bend the bundled experience to match your product without losing MediaSFU's hardened real-time logic.

Shared component props (applies to every MediaSFU UI component)

| Prop | Type | Default | What it does | | --- | --- | --- | --- | | PrejoinPage | (options) => React.ReactNode | WelcomePage | Swap in a custom pre-join experience. Receives unified pre-join options so you can add branding, legal copy, or warm-up flows. | | localLink | string | "" | Point the SDK at your self-hosted MediaSFU server. Leave empty when using MediaSFU Cloud. | | connectMediaSFU | boolean | true | Toggle automatic socket/WebRTC connections. Set to false when you only need the UI shell. | | credentials | { apiUserName: string; apiKey: string } | { apiUserName: "", apiKey: "" } | Supply cloud credentials without hard-coding them elsewhere. | | useLocalUIMode | boolean | false | Run the interface in local/demo mode with no remote signaling. | | seedData, useSeed | SeedData, boolean | {}, false | Pre-populate the UI for demos, snapshot tests, or onboarding tours. | | imgSrc | string | https://mediasfu.com/images/logo192.png | Default artwork used across pre-join and modal flows. | | sourceParameters | Record<string, unknown> | undefined | Shared helper bag (media devices, participant helpers, layout handlers). Pair with updateSourceParameters to mirror the SDK's internal utilities. | | updateSourceParameters | (helpers) => void | undefined | Receive the latest helper bundle so you can bridge MediaSFU logic into your own components. | | returnUI | boolean | true | When false, mount the logic only—a perfect stepping stone to a fully bespoke interface. | | noUIPreJoinOptions | CreateMediaSFURoomOptions \| JoinMediaSFURoomOptions | undefined | Feed pre-join data when returnUI is false and you want to bypass the on-screen wizard. | | joinMediaSFURoom, createMediaSFURoom | Functions | undefined | Inject your own networking layers for joining or creating rooms. | | customComponent | CustomComponentType | undefined | Replace the entire UI while retaining transports, sockets, and helpers. | | customVideoCard, customAudioCard, customMiniCard | Factories | undefined | Override participant card renders to add metadata, CTAs, or badges. | | containerStyle | React.CSSProperties | undefined | Apply inline styles to the root wrapper (dashboards, split views, etc.). | | uiOverrides | MediasfuUICustomOverrides | undefined | Targeted component/function overrides described below. |

Power combo: Set returnUI={false} to run MediaSFU logic headless, capture helpers via updateSourceParameters, and selectively bring UI pieces back with uiOverrides. That gives you progressive migration with minimal code churn.

import type { MediasfuUICustomOverrides } from "mediasfu-reactnative";

const overrides: MediasfuUICustomOverrides = { /* ... */ };

Bring the types into your project to unlock full IntelliSense for every override slot.

Custom UI Playbook

Use a toggle-driven "playbook" component to experiment with MediaSFU's customization layers. Flip a couple of booleans and you can watch the SDK jump between prebuilt layouts, headless logic, or a fully bespoke workspace driven by customComponent.

What the playbook demonstrates

  • Connection presets: toggle connectionScenario between cloud, hybrid, or ce to swap credentials, local links, and connection modes in one place.
  • Experience selector: the selectedExperience switch renders MediasfuGeneric, MediasfuBroadcast, MediasfuWebinar, MediasfuConference, or MediasfuChat without touching the rest of your stack.
  • UI strategy flags: booleans like showPrebuiltUI, enableFullCustomUI, and enableNoUIPreJoin demonstrate how to run the MediaSFU logic with or without the bundled UI.
  • Layered overrides: toggles enable the custom video/audio/mini cards, drop-in uiOverrides for layout and modal surfaces, container styling, and backend proxy helpers.
  • Custom workspace demo: a customComponent receives live MediaSFU helpers so you can build dashboards, CRM surfaces, or any bespoke host interface.
  • Debug panel & helpers: optional JSON panel exposes the updateSourceParameters payload so you can see exactly what to wire into your own components.

Try it quickly

const connectionScenario: "cloud" | "hybrid" | "ce" = "cloud";
const selectedExperience = "generic" as const;
const showPrebuiltUI = true;
const enableFullCustomUI = false;

const connectionPresets = {
  cloud: { credentials: { apiUserName: "demo", apiKey: "demo" }, localLink: "", connectMediaSFU: true },
  hybrid: { credentials: { apiUserName: "demo", apiKey: "demo" }, localLink: "http://localhost:3000", connectMediaSFU: true },
  ce: { credentials: undefined, localLink: "http://localhost:3000", connectMediaSFU: false },
};

const Experience = {
  generic: MediasfuGeneric,
  broadcast: MediasfuBroadcast,
  webinar: MediasfuWebinar,
  conference: MediasfuConference,
  chat: MediasfuChat,
}[selectedExperience];

export const CustomUIPlaybook = () => {
  const overrides = useMemo(() => ({
    mainContainer: enableFullCustomUI
      ? {
          render: (props) => (
            <View style={{ borderWidth: 4, borderColor: 'purple', borderRadius: 24, padding: 16 }}>
              <MainContainerComponent {...props} />
            </View>
          ),
        }
      : undefined,
  }), [enableFullCustomUI]);

  const current = connectionPresets[connectionScenario];

  return (
    <Experience
      {...current}
      showPrebuiltUI={showPrebuiltUI}
      uiOverrides={overrides}
      containerStyle={{ background: "linear-gradient(135deg, #0f172a, #1e3a8a)", minHeight: "100%" }}
    />
  );
};

Toggle the configuration values at the top of the playbook and watch the UI reconfigure instantly. It's the fastest path to understand MediaSFU's override surface before you fold the patterns into your production entrypoint.

Passing custom props and UI overrides

Use the same playbook to validate bespoke cards, override bundles, and fully custom workspaces before you move them into production code:

const videoCard: CustomVideoCardType = (props) => (
  <VideoCard
    {...props}
    customStyle={{
      borderRadius: 20,
      border: "3px solid #4c1d95",
      boxShadow: "0 28px 65px rgba(76,29,149,0.35)",
      background: "linear-gradient(140deg, rgba(15,23,42,0.78), rgba(30,64,175,0.45))",
      ...(props.customStyle ?? {}),
    }}
  />
);

const audioCard: CustomAudioCardType = (props) => (
  <AudioCard
    {...props}
    barColor="#22c55e"
    customStyle={{ borderRadius: 22, background: "rgba(34,197,94,0.1)" }}
  />
);

const miniCard: CustomMiniCardType = (props) => (
  <MiniCard
    {...props}
    renderContainer={({ defaultContainer }) => (
      <View style={{ display: "flex", alignItems: "center", justifyContent: "center", height: "100%" }}>
        {defaultContainer}
      </View>
    )}
  />
);

const uiOverrides = useMemo<MediasfuUICustomOverrides>(() => ({
  mainContainer: {
    render: (props) => (
      <View style={{ borderWidth: 4, borderColor: 'rgba(139,92,246,0.8)', borderRadius: 28, padding: 16 }}>
        <MainContainerComponent {...props} />
      </View>
    ),
  },
  menuModal: {
    component: (modalProps) => <MenuModal {...modalProps} variant="glass" />,
  },
  consumerResume: {
    wrap: (original) => async (params) => {
      const startedAt = performance.now();
      const result = await original(params);
      analytics.track("consumer_resume", {
        durationMs: performance.now() - startedAt,
        consumerId: params?.consumer?.id,
      });
      return result;
    },
  },
}), []);

return (
  <Experience
    {...current}
    customVideoCard={videoCard}
    customAudioCard={audioCard}
    customMiniCard={miniCard}
    customComponent={enableFullCustomUI ? CustomWorkspace : undefined}
    containerStyle={{ background: "#0f172a", borderRadius: 32, overflow: "hidden" }}
    uiOverrides={uiOverrides}
  />
);

Because the playbook surfaces updateSourceParameters, you can also log or snapshot the helper bundle (getParticipantMedia, toggleMenuModal, showAlert, and more) to ensure your custom UI always receives the hooks it expects.

uiOverrides map — override keys at a glance

Each key accepts a CustomComponentOverride<Props> object with optional component and render fields. You can fully replace the default implementation or wrap it while forwarding props.

Layout & control surfaces

| Key | Default component | Typical use | | --- | --- | --- | | mainContainer | MainContainerComponent | Inject theming providers or dashboard layouts. | | mainAspect | MainAspectComponent | Tune how the main region splits space. | | mainScreen | MainScreenComponent | Orchestrate hero video + gallery interplay. | | mainGrid | MainGridComponent | Modify layout or layering of primary participants. | | subAspect | SubAspectComponent | Restyle fixed control strips in webinar/conference modes. | | otherGrid | OtherGridComponent | Change presentation of off-stage attendees. | | flexibleGrid, flexibleGridAlt | FlexibleGrid | Implement AI-driven or branded array layouts. | | flexibleVideo | FlexibleVideo | Add captions, watermarks, or overlays to highlighted speakers. | | audioGrid | AudioGrid | Customise audio-only attendee presentation. | | pagination | Pagination | Introduce infinite scroll or auto-cycling carousels. | | controlButtons | ControlButtonsComponent | Rebrand the primary action bar. | | controlButtonsAlt | ControlButtonsAltComponent | Control secondary button clusters. | | controlButtonsTouch | ControlButtonsComponentTouch | Deliver mobile-first controls (used heavily by MediasfuChat). |

Participant cards & widgets

| Key | Default component | Typical use | | --- | --- | --- | | videoCard | VideoCard | Add host badges, reactions, or CRM overlays. | | audioCard | AudioCard | Swap avatars or expose spoken-language info. | | miniCard | MiniCard | Customize thumbnails in picture-in-picture modes. | | miniAudio | MiniAudio | Re-style the audio-only mini indicators. | | meetingProgressTimer | MeetingProgressTimer | Replace the elapsed-time widget with countdowns or milestones. | | miniAudioPlayer | MiniAudioPlayer | Provide alternative UI for recorded clip playback. |

Modals, dialogs, and collaboration surfaces

| Key | Default component | Typical use | | --- | --- | --- | | loadingModal | LoadingModal | Show branded skeletons while connecting. | | alert | AlertComponent | Route alerts through your notification system. | | menuModal | MenuModal | Redesign quick-action trays. | | eventSettingsModal | EventSettingsModal | Extend host tools with your own settings. | | requestsModal | RequestsModal | Build moderation queues tailored to your workflows. | | waitingRoomModal | WaitingRoomModal | Deliver custom waiting-room experiences. | | coHostModal | CoHostModal | Manage co-hosts with bespoke UX. | | mediaSettingsModal | MediaSettingsModal | Embed device tests or instructions. | | participantsModal | ParticipantsModal | Introduce advanced filters, search, or notes. | | messagesModal | MessagesModal | Drop in your full-featured chat module. | | displaySettingsModal | DisplaySettingsModal | Let users pick layouts, themes, or captions. | | confirmExitModal | ConfirmExitModal | Meet compliance wording requirements. | | confirmHereModal | ConfirmHereModal | Customize attendance confirmations for webinars. | | shareEventModal | ShareEventModal | Add referral codes or QR sharing. | | recordingModal | RecordingModal | Tailor recording confirmation flows. | | pollModal | PollModal | Integrate your polling/quiz engine. | | backgroundModal | BackgroundModal | Hook AI background replacement or brand presets. | | breakoutRoomsModal | BreakoutRoomsModal | Implement drag-and-drop or AI room suggestions. | | configureWhiteboardModal | ConfigureWhiteboardModal | Adjust collaboration permissions before launch. | | whiteboard | Whiteboard | Replace with your whiteboard provider. | | screenboard | Screenboard | Modify shared-screen annotation layers. | | screenboardModal | ScreenboardModal | Reimagine how users enable shared annotations. |

Entry flows & custom renderers

| Key | Default component | Typical use | | --- | --- | --- | | welcomePage | WelcomePage | Provide a fully branded welcome/marketing splash. | | preJoinPage | PrejoinPage | Override the wizard used before joining live sessions. | | customMenuButtonsRenderer | ControlButtonsAltComponent | Supply a bespoke renderer for menu button groups without overriding each button. |

Function overrides

| Key | Default function | Typical use | | --- | --- | --- | | consumerResume | consumerResume | Wrap errors, capture analytics, or rate-limit consumer resume behavior. | | addVideosGrid | addVideosGrid | Replace participant ordering or layout heuristics on the fly. |

Function overrides support { implementation, wrap }. Provide implementation for a full replacement, or wrap to intercept the default behavior before/after it runs.

Example: swap the chat modal and theme the controls

import { MediasfuGeneric } from "mediasfu-reactnative";
import { MyChatModal } from "./ui/MyChatModal";
import { MyControls } from "./ui/MyControls";

const uiOverrides = {
  messagesModal: {
    component: MyChatModal,
  },
  controlButtons: {
    render: (props) => <MyControls {...props} variant="glass" />,
  },
};

export const MyMeeting = () => (
  <MediasfuGeneric credentials={credentials} uiOverrides={uiOverrides} />
);

Example: wrap a MediaSFU helper instead of replacing it

const uiOverrides = {
  consumerResume: {
    wrap: (original) => async (params) => {
      const startedAt = performance.now();
      const result = await original(params);
      analytics.track("consumer_resume", {
        durationMs: performance.now() - startedAt,
        consumerId: params?.consumer?.id,
      });
      return result;
    },
  },
};

<MediasfuConference uiOverrides={uiOverrides} />;

The same override hooks power the newly refreshed MediasfuWebinar and MediasfuChat layouts, so you can guarantee a unified experience across events, webinars, or chat-first rooms.


MediaSFU offers a cutting-edge streaming experience that empowers users to customize their recordings and engage their audience with high-quality streams. Whether you're a content creator, educator, or business professional, MediaSFU provides the tools you need to elevate your streaming game.


MediaSFU React Native Module Documentation

🚀 Quick Access to New Features

Media Device & Stream Utilities

The SDK now includes powerful utility methods for advanced media control:

getMediaDevicesList - Enumerate available cameras and microphones with automatic permission handling:

const cameras = await parameters.getMediaDevicesList('videoinput');
const microphones = await parameters.getMediaDevicesList('audioinput');

getParticipantMedia - Retrieve specific participant's video or audio stream from the session:

import { getParticipantMedia } from 'mediasfu-reactnative';

const videoStream = getParticipantMedia({
  participantId: 'producer-123',
  mediaType: 'video',
  parameters: sourceParameters,
});

These utilities enable advanced features like custom device selection interfaces, participant stream monitoring, and dynamic media routing. See full documentation.


Unlock the Power of MediaSFU Community Edition

MediaSFU Community Edition is free and open-source—perfect for developers who want to run their own media server without upfront costs. With robust features and simple setup, you can launch your media solution in minutes. Ready to scale? Upgrade seamlessly to MediaSFU Cloud for enterprise-grade performance and global scalability.

Get started now on GitHub!

✅ React Native SDK Setup Guide

Watch the React Native SDK Setup Guide
🎥 Watch the React Native SDK Setup Guide


Table of Contents

Features

MediaSFU's React Native SDK comes with a host of powerful features out of the box:

  1. Breakout Rooms: Create multiple sub-meetings within a single session to enhance collaboration and focus.
  2. Pagination: Efficiently handle large participant lists with seamless pagination.
  3. Polls: Conduct real-time polls to gather instant feedback from participants.
  4. Media Access Requests Management: Manage media access requests with ease to ensure smooth operations.
  5. Video Effects: Apply various video effects, including virtual backgrounds, to enhance the visual experience.
  6. Chat (Direct & Group): Facilitate communication with direct and group chat options.
  7. Cloud Recording (track-based): Customize recordings with track-based options, including watermarks, name tags, background colors, and more.
  8. Managed Events: Manage events with features to handle abandoned and inactive participants, as well as enforce time and capacity limits.
  9. AI Phone Agents: Integrate AI-powered phone agents for automated customer interactions at a fraction of the cost of traditional providers.

🆕 New Advanced Media Access

The SDK now includes powerful utility methods for fine-grained control over media devices and participant streams:

  • getMediaDevicesList: Enumerate available cameras and microphones with permission handling
  • getParticipantMedia: Retrieve specific participant's video or audio streams by ID or name

These utilities enable advanced features like device selection interfaces, participant stream monitoring, and custom media routing. Learn more in the Media Device & Stream Utilities section.

Getting Started

This section will guide users through the initial setup and installation of the npm module.

Note: this is specifically for React-Native-CLI. If you are integrating into a React Native Expo app, the best option is to use the core mediasfu-reactnative-expo package, which you can find on npm at mediasfu-reactnative-expo.

Documentation Reference

For comprehensive documentation on the available methods, components, and functions, please visit mediasfu.com. This resource provides detailed information for this guide and additional documentation.

Installation

Instructions on how to install the module using npm for a standard React Native (non-Expo) project.

1. Add the Package to Your Project

npm install mediasfu-reactnative

1.1 Important Installation Notes for React Native

🚫 Avoid Using --force or --legacy-peer-deps

Using these flags can override important dependency checks, potentially causing unstable builds or unexpected behavior.

  • Why Avoid Them?
    They bypass compatibility checks, which can introduce bugs or conflicts within your project.

⚙️ Use Package Overrides (Recommended)

If you encounter peer dependency conflicts, use the overrides field in your package.json instead of forcing installations.

Example of Safe Overrides:
{
  "overrides": {
    "some-package": {
      "dependency-name": "^1.2.3"
    }
  }
}
  • Why This Works:
    Overrides let you resolve conflicts safely without compromising the integrity of your project.

🚩 If You Absolutely Need to Use --force or --legacy-peer-deps

  • Some peer dependencies might be skipped.
  • You’ll need to manually install them to avoid runtime errors.
🔑 Install the Required Peer Dependencies:
npm install \
"@react-native-async-storage/async-storage@^2.0.0" \
"@react-native-clipboard/clipboard@^1.14.3" \
"@react-native-community/slider@^4.5.5" \
"@react-native-picker/picker@^2.9.0" \
"@react-navigation/native@^6.1.18" \
"@react-navigation/native-stack@^6.11.0" \
"mediasoup-client@^3.16.0" \
"react@^18.3.1" \
"react-color@^2.19.3" \
"react-native@^0.76.0" \
"react-native-gesture-handler@^2.20.2" \
"react-native-orientation-locker@^1.7.0" \
"react-native-permissions@^5.0.2" \
"react-native-picker-select@^9.3.1" \
"react-native-reanimated@^3.16.1" \
"react-native-safe-area-context@^4.12.0" \
"react-native-screens@^3.35.0" \
"react-native-sound@^0.11.2" \
"react-native-status-bar-height@^2.6.0" \
"react-native-vector-icons@^10.2.0" \
"react-native-video@^6.7.0" \
"react-native-webrtc@^124.0.4" \
"react-native-webrtc-web-shim@^1.0.7" \
"reanimated-color-picker@^3.0.4" \
"socket.io-client@^4.8.1"
  • Why This Is Important:
    These peer dependencies are critical for mediasfu-reactjs to function correctly within React Native.

🔍 How to Check for Peer Dependencies

  1. Open your package.json.

  2. Look for the peerDependencies section:

    "peerDependencies": {
      "@react-native-async-storage/async-storage": "^2.0.0",
      "@react-native-clipboard/clipboard": "^1.14.3",
      "@react-native-community/slider": "^4.5.5",
      "@react-native-picker/picker": "^2.9.0",
      "@react-navigation/native": "^6.1.18",
      "@react-navigation/native-stack": "^6.11.0",
      "mediasoup-client": "^3.16.0",
      "react": "^18.3.1",
      "react-color": "^2.19.3",
      "react-native": "^0.76.0",
      "react-native-gesture-handler": "^2.20.2",
      "react-native-orientation-locker": "^1.7.0",
      "react-native-permissions": "^5.0.2",
      "react-native-picker-select": "^9.3.1",
      "react-native-reanimated": "^3.16.1",
      "react-native-safe-area-context": "^4.12.0",
      "react-native-screens": "^3.35.0",
      "react-native-sound": "^0.11.2",
      "react-native-status-bar-height": "^2.6.0",
      "react-native-vector-icons": "^10.2.0",
      "react-native-video": "^6.7.0",
      "react-native-webrtc": "^124.0.4",
      "react-native-webrtc-web-shim": "^1.0.7",
      "reanimated-color-picker": "^3.0.4",
      "socket.io-client": "^4.8.1"
    }
  3. Ensure all are installed. If not, run the install command above.


Final Recommendations

  • Always try to resolve conflicts using overrides first.
  • Only use --force or --legacy-peer-deps as a last resort.

2.1 Obtain an API Key (If Required)

You can get your API key by signing up or logging into your account at mediasfu.com.

2.2 Self-Hosting MediaSFU

If you plan to self-host MediaSFU or use it without MediaSFU Cloud services, you don't need an API key. You can access the open-source version of MediaSFU from the MediaSFU Open Repository.

This setup allows full flexibility and customization while bypassing the need for cloud-dependent credentials.

3. Configure Your Project

Before proceeding, ensure that your project is properly configured to work with mediasfu-reactnative. Follow the steps below to set up the necessary configuration files.

a. Configure metro.config.js

Ensure your metro.config.js file includes the correct settings:

const { getDefaultConfig, mergeConfig } = require('@react-native/metro-config');

/**
 * Metro configuration
 * https://reactnative.dev/docs/metro
 *
 * @type {import('metro-config').MetroConfig}
 */
const config = {};

module.exports = mergeConfig(getDefaultConfig(__dirname), config);

b. Configure babel.config.js

Your babel.config.js should include the necessary presets and plugins for React Native Reanimated. Here is an example configuration:

module.exports = {
  presets: ['module:@react-native/babel-preset'],
  plugins: [
    '@babel/plugin-transform-block-scoping',
    'react-native-reanimated/plugin',
  ],
};

c. Add Permissions

To support WebRTC video, audio, and Bluetooth functionalities, you need to add the following permissions to your project.

Android

Add the following permissions and features to your AndroidManifest.xml:

<!-- Permissions -->
<uses-permission android:name="android.permission.INTERNET" />
<uses-permission android:name="android.permission.CAMERA" />
<uses-permission android:name="android.permission.RECORD_AUDIO" />
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
<uses-permission android:name="android.permission.CHANGE_NETWORK_STATE" />
<uses-permission android:name="android.permission.MODIFY_AUDIO_SETTINGS" />
<uses-permission android:name="android.permission.BLUETOOTH" android:maxSdkVersion="30" />
<uses-permission android:name="android.permission.BLUETOOTH_ADMIN" android:maxSdkVersion="30" />
<uses-permission android:name="android.permission.BLUETOOTH_CONNECT" />

<!-- Features -->
<uses-feature android:name="android.hardware.camera" />
<uses-feature android:name="android.hardware.camera.autofocus" />
<uses-feature android:name="android.hardware.audio.output" />
<uses-feature android:name="android.hardware.microphone" />
iOS

Add the following permissions to your Info.plist:

<!-- Permissions -->
<key>NSCameraUsageDescription</key>
<string>Your message to the user about why the app needs camera access</string>
<key>NSMicrophoneUsageDescription</key>
<string>Your message to the user about why the app needs microphone access</string>
<key>NSBluetoothAlwaysUsageDescription</key>
<string>Your message to the user about why the app needs Bluetooth access</string>

Note: Ensure to customize the permission descriptions to inform users why these permissions are required.

Other Platforms

If you are targeting other platforms, make sure to add the relevant permissions and configurations as needed.

4. Install Required Dependencies

The following dependencies should be automatically installed with mediasfu-reactnative. However, if they are not, you can install them manually:

npm install @react-native-clipboard/clipboard @react-native-async-storage/async-storage react-native-webrtc react-native-safe-area-context react-native-orientation-locker react-native-picker-select @react-native-picker/picker react-native-reanimated react-native-gesture-handler react-native-sound

5. Configure Vector Icons

To ensure that react-native-vector-icons work correctly, you need to link the fonts.

Android

In your android/app/build.gradle file, add the following line:

apply from: "../../node_modules/react-native-vector-icons/fonts.gradle"

iOS

  1. Open your project in Xcode.
  2. Drag the react-native-vector-icons folder from node_modules into your project.
  3. Ensure that the fonts are included in your project’s Build Phases under Copy Bundle Resources.

For detailed instructions, refer to the react-native-vector-icons documentation.

6. Complete the Setup

After completing the above steps, you can proceed to set up and run your project.

  • Start the Metro Bundler:

    npx react-native start
  • Run the Application:

    For Android:

    npx react-native run-android

    For iOS:

    npx react-native run-ios

Additional Configuration (Optional)

If you encounter any issues during setup, refer to the Troubleshooting section for common solutions.

For more detailed information, visit the mediasfu-reactnative GitHub Repository and the React Native Documentation.


📱 React Native SDK Comprehensive Guide

This comprehensive guide provides clear, progressive learning paths from beginner to advanced usage. Each section builds upon the previous one with practical examples and detailed explanations.

Table of Contents - SDK Guide


Quick Start (5 Minutes)

Get your first MediaSFU app running in just a few minutes.

Step 1: Install the Package

npm install mediasfu-reactnative

Step 2: Import and Use

import React from 'react';
import { MediasfuGeneric } from 'mediasfu-reactnative';

const App = () => {
  // Option 1: Use without credentials (for testing/development)
  return <MediasfuGeneric />;

  // Option 2: Use with MediaSFU Cloud credentials
  // const credentials = { apiUserName: 'your_username', apiKey: 'your_api_key' };
  // return <MediasfuGeneric credentials={credentials} />;
};

export default App;

Step 3: Run Your App

npx react-native run-android
# or
npx react-native run-ios

That's it! You now have a fully functional video conferencing app with:

  • ✅ Video and audio streaming
  • ✅ Screen sharing
  • ✅ Chat messaging
  • ✅ Participant management
  • ✅ Recording capabilities
  • ✅ Breakout rooms
  • ✅ Polls

Understanding MediaSFU Architecture

Before diving deeper, let's understand how MediaSFU is structured. This knowledge will help you make better decisions when building your application.

The Three-Layer Architecture

┌─────────────────────────────────────────────┐
│      Your React Native Application          │
│  (App.js, screens, navigation, logic)       │
└─────────────────────────────────────────────┘
                    ↓
┌─────────────────────────────────────────────┐
│       MediaSFU Components Layer             │
│  (MediasfuGeneric, MediasfuBroadcast, etc.) │
│       - Pre-built UI components              │
│       - Event handling                       │
│       - State management                     │
└─────────────────────────────────────────────┘
                    ↓
┌─────────────────────────────────────────────┐
│       MediaSFU Core Methods Layer           │
│   (Stream control, room management,         │
│    WebRTC handling, socket communication)   │
└─────────────────────────────────────────────┘
                    ↓
┌─────────────────────────────────────────────┐
│       MediaSFU Backend Services             │
│ (MediaSFU Cloud or Community Edition)       │
└─────────────────────────────────────────────┘

Event Room Types

MediaSFU provides 5 specialized room types, each optimized for specific use cases:

| Room Type | Best For | Key Features | |-----------|----------|--------------| | MediasfuGeneric | General purpose meetings | Flexible layout, all features enabled | | MediasfuBroadcast | Live streaming events | Optimized for one-to-many communication | | MediasfuWebinar | Educational sessions | Presenter focus, Q&A features | | MediasfuConference | Business meetings | Equal participant layout, collaboration tools | | MediasfuChat | Interactive discussions | Chat-first interface, quick connections |

// Choose the right room type for your use case
import { 
  MediasfuGeneric,
  MediasfuWebinar, 
  MediasfuBroadcast, 
  MediasfuConference,
  MediasfuChat
} from 'mediasfu-reactnative';

// For a webinar
<MediasfuWebinar credentials={credentials} />

// For a broadcast  
<MediasfuBroadcast credentials={credentials} />

// For a conference
<MediasfuConference credentials={credentials} />

The Three Usage Modes

MediaSFU offers three progressive levels of customization. Understanding these modes is crucial for choosing the right approach for your project.

Mode 1: Default UI (Simplest) ⭐ Best for Beginners

Use MediaSFU's complete pre-built interface - perfect for rapid development.

import React from 'react';
import { MediasfuGeneric } from 'mediasfu-reactnative';

const App = () => {
  const credentials = { 
    apiUserName: 'your_username', 
    apiKey: 'your_api_key' 
  };
  
  return <MediasfuGeneric credentials={credentials} />;
};

export default App;

When to use:

  • ✅ Prototyping or MVP development
  • ✅ Need a production-ready UI quickly
  • ✅ Standard video conferencing features are sufficient
  • ✅ Want to minimize development time

Advantages:

  • Zero UI development needed
  • All features work out of the box
  • Automatic responsive layouts
  • Professional appearance

Mode 2: Custom UI with MediaSFU Backend (Most Flexible) ⭐ Best for Custom Brands

Build your own UI while using MediaSFU's powerful backend infrastructure.

import React, { useState, useEffect } from 'react';
import { View, TouchableOpacity, Text } from 'react-native';
import { MediasfuGeneric } from 'mediasfu-reactnative';

const App = () => {
  const [sourceParameters, setSourceParameters] = useState(null);
  const credentials = { apiUserName: 'your_username', apiKey: 'your_api_key' };

  const updateSourceParameters = (params) => {
    setSourceParameters(params);
  };

  return (
    <View style={{ flex: 1 }}>
      <MediasfuGeneric 
        returnUI={false}
        sourceParameters={sourceParameters}
        updateSourceParameters={updateSourceParameters}
        credentials={credentials}
        noUIPreJoinOptions={{ 
          action: 'create',
          userName: 'Your Name',
          capacity: 50,
          duration: 30,
          eventType: 'conference'
        }}
      />
      
      {/* Your completely custom UI */}
      {sourceParameters && (
        <View style={styles.customControls}>
          <TouchableOpacity 
            onPress={() => sourceParameters.clickVideo({ 
              parameters: sourceParameters 
            })}
            style={styles.controlButton}
          >
            <Text>{sourceParameters.videoAlreadyOn ? 'Stop Video' : 'Start Video'}</Text>
          </TouchableOpacity>
          
          <TouchableOpacity 
            onPress={() => sourceParameters.clickAudio({ 
              parameters: sourceParameters 
            })}
            style={styles.controlButton}
          >
            <Text>{sourceParameters.audioAlreadyOn ? 'Mute' : 'Unmute'}</Text>
          </TouchableOpacity>

          {/* Display participant count */}
          <Text style={styles.participantCount}>
            {sourceParameters.participants.length} Participants
          </Text>
        </View>
      )}
    </View>
  );
};

const styles = {
  customControls: {
    position: 'absolute',
    bottom: 20,
    left: 20,
    right: 20,
    backgroundColor: 'rgba(0,0,0,0.8)',
    padding: 15,
    borderRadius: 10,
  },
  controlButton: {
    backgroundColor: '#4CAF50',
    padding: 12,
    borderRadius: 8,
    marginVertical: 5,
    alignItems: 'center',
  },
  participantCount: {
    color: 'white',
    fontSize: 16,
    marginTop: 10,
  }
};

export default App;

When to use:

  • ✅ Need complete control over UI/UX
  • ✅ Building a custom branded experience
  • ✅ Integrating into existing app design
  • ✅ Want to position controls differently

What you get:

  • Access to all MediaSFU methods via sourceParameters
  • Full control over when and how to display UI
  • Ability to create completely custom layouts
  • Access to real-time room state and participant data

Mode 3: Component Replacement (Balanced) ⭐ Best for Partial Customization

Replace specific MediaSFU components while keeping the rest of the infrastructure.

import React from 'react';
import { View, Text, StyleSheet } from 'react-native';
import { 
  MediasfuGeneric, 
  FlexibleVideo, 
  FlexibleGrid,
  AudioGrid
} from 'mediasfu-reactnative';

// Your custom main screen component
function CustomMainScreen({ parameters }) {
  return (
    <View style={styles.container}>
      {/* Custom header */}
      <View style={styles.header}>
        <Text style={styles.roomName}>{parameters.roomName}</Text>
        <Text style={styles.participantCount}>
          {parameters.participants.length} participants
        </Text>
      </View>
      
      {/* Use MediaSFU's FlexibleVideo for main display */}
      <View style={styles.mainVideo}>
        <FlexibleVideo 
          customWidth={parameters.componentSizes.mainWidth}
          customHeight={parameters.componentSizes.mainHeight}
          parameters={parameters}
        />
      </View>
      
      {/* Use MediaSFU's FlexibleGrid for participants */}
      <View style={styles.participantGrid}>
        <FlexibleGrid 
          customWidth={parameters.componentSizes.otherWidth}
          customHeight={parameters.componentSizes.otherHeight}
          parameters={parameters}
        />
      </View>

      {/* Show audio-only participants */}
      <View style={styles.audioContainer}>
        <AudioGrid parameters={parameters} />
      </View>
    </View>
  );
}

const App = () => {
  const credentials = { apiUserName: 'your_username', apiKey: 'your_api_key' };
  
  return (
    <MediasfuGeneric 
      credentials={credentials}
      customComponent={CustomMainScreen}
    />
  );
};

const styles = StyleSheet.create({
  container: {
    flex: 1,
    backgroundColor: '#1a1a1a',
  },
  header: {
    backgroundColor: '#2d2d2d',
    padding: 15,
    flexDirection: 'row',
    justifyContent: 'space-between',
  },
  roomName: {
    color: 'white',
    fontSize: 18,
    fontWeight: 'bold',
  },
  participantCount: {
    color: '#4CAF50',
    fontSize: 14,
  },
  mainVideo: {
    flex: 3,
  },
  participantGrid: {
    flex: 2,
  },
  audioContainer: {
    height: 80,
    backgroundColor: '#2d2d2d',
  },
});

export default App;

When to use:

  • ✅ Need custom main interface but want to keep MediaSFU's components
  • ✅ Partial customization with minimal effort
  • ✅ Want to maintain MediaSFU's functionality while customizing layout
  • ✅ Need to rearrange existing components

What you get:

  • Replace only the main screen component
  • Access to all MediaSFU's sub-components
  • parameters object with full access to methods
  • Automatic handling of WebRTC, sockets, and state

Parameters Object: Your Control Center

The parameters object (also called sourceParameters in Mode 2) is your gateway to all MediaSFU functionality. Understanding this object is crucial for advanced customization.

Key Categories:

// The parameters object structure
{
  // === MEDIA CONTROLS ===
  clickVideo: (options) => {},              // Toggle video on/off
  clickAudio: (options) => {},              // Toggle audio on/off
  clickScreenShare: (options) => {},        // Toggle screen sharing
  
  // === ROOM STATE ===
  roomName: 'meeting-room-123',            // Current room identifier
  member: 'John Doe',                      // Current user's name
  islevel: '2',                            // User role ('0'=participant, '2'=host)
  participants: [],                        // Array of all participants
  
  // === MEDIA STREAMS ===
  allVideoStreams: [],                     // All video producer streams
  allAudioStreams: [],                     // All audio producer streams
  localStream: null,                       // Your local media stream
  
  // === UI STATE ===
  videoAlreadyOn: false,                   // Is your video currently on?
  audioAlreadyOn: false,                   // Is your audio currently on?
  
  // === RECORDING ===
  recordStarted: false,                    // Is recording active?
  startRecording: (options) => {},         // Start recording
  stopRecording: (options) => {},          // Stop recording
  
  // === CHAT & MESSAGING ===
  messages: [],                            // All chat messages
  sendMessage: (options) => {},            // Send a message
  
  // === DEVICE MANAGEMENT ===
  getMediaDevicesList: (type) => {},       // Get available devices
  
  // And 180+ more properties and methods...
}

Access patterns in different modes:

// Mode 1 (Default UI): Parameters managed internally
// You don't need to access them directly

// Mode 2 (Custom UI): Access via sourceParameters state
const [sourceParameters, setSourceParameters] = useState(null);
sourceParameters.clickVideo({ parameters: sourceParameters });

// Mode 3 (Component Replacement): Passed to your component
function CustomComponent({ parameters }) {
  parameters.clickVideo({ parameters });
}

Core Concepts & Components

Now that you understand the architecture, let's explore the building blocks in detail.

Display Components

MediaSFU provides powerful, ready-to-use components for organizing and displaying media streams.

FlexibleVideo - Main video display area

The FlexibleVideo component automatically handles displaying the main video content.

import { FlexibleVideo } from 'mediasfu-reactnative';

<FlexibleVideo
  customWidth={screenWidth}
  customHeight={600}
  parameters={parameters}
/>

Features:

  • Automatically displays main presenter or screen share
  • Smooth transitions between video sources
  • Responsive sizing
  • Handles aspect ratio automatically

When to use: Primary video display area, screen sharing, featured speaker view

FlexibleGrid - Participant grid layout

Creates an intelligent grid layout for displaying multiple participants.

import { FlexibleGrid } from 'mediasfu-reactnative';

<FlexibleGrid
  customWidth={screenWidth}
  customHeight={800}
  parameters={parameters}
/>

Features:

  • Intelligent auto-sizing (2x2, 3x3, 4x4 grids, etc.)
  • Automatic pagination for large participant lists
  • Dynamic reflow on orientation change
  • Optimized rendering performance

When to use: Gallery view, displaying multiple participants, conference layouts

AudioGrid - Audio-only participants

Displays participants who have joined without video.

import { AudioGrid } from 'mediasfu-reactnative';

<AudioGrid parameters={parameters} />

Features:

  • Compact display for audio-only users
  • Visual audio level indicators
  • Name/initial displays
  • Space-efficient layout

When to use: Audio-only participants, minimizing screen space, podcast-style recordings

Control Components

MediaSFU provides pre-built control components with different layouts:

ControlButtonsComponentTouch - Touch-optimized controls

import { ControlButtonsComponentTouch } from 'mediasfu-reactnative';

<ControlButtonsComponentTouch
  parameters={parameters}
  position="bottom"
  direction="horizontal"
/>

Includes:

  • Mute/Unmute microphone
  • Start/Stop video
  • Screen share toggle
  • Participants list
  • Chat button
  • End call button

Modal Components

MediaSFU includes pre-built modals for various features:

import {
  ParticipantsModal,      // Participant management
  MessagesModal,          // Chat interface
  SettingsModal,          // Application settings
  RecordingModal,         // Recording controls
  PollModal,              // Polls interface
  BreakoutRoomsModal,     // Breakout rooms management
} from 'mediasfu-reactnative';

Controlling modals:

// Show participants modal
parameters.updateIsParticipantsModalVisible(true);

// Show chat
parameters.updateIsMessagesModalVisible(true);

// Show settings
parameters.updateIsSettingsModalVisible(true);

Working with Methods

MediaSFU provides 200+ methods for controlling every aspect of your real-time communication experience.

Media Control Methods

Video Control

// Toggle video on/off
await parameters.clickVideo({
  parameters: parameters,
});

// Check current video state
console.log('Video is:', parameters.videoAlreadyOn ? 'ON' : 'OFF');

// Switch between front and back camera
await parameters.switchVideoAlt({
  parameters: parameters,
});

Audio Control

// Toggle audio on/off
await parameters.clickAudio({
  parameters: parameters,
});

// Mute specific participant (host only)
if (parameters.islevel === '2') {
  await parameters.muteParticipants({
    participant: {
      id: 'participant-id',
      name: 'John Doe',
    },
    parameters: parameters,
  });
}

Screen Sharing

// Start/stop screen sharing
await parameters.clickScreenShare({
  parameters: parameters,
});

// Check if screen sharing is active
console.log('Screen sharing:', parameters.screenAlreadyOn);

Device Management Methods

// Get all available cameras
const cameras = await parameters.getMediaDevicesList('videoinput');
console.log('Available cameras:', cameras);

// Get all available microphones
const microphones = await parameters.getMediaDevicesList('audioinput');
console.log('Available microphones:', microphones);

// Switch to specific camera
await parameters.switchUserVideo({
  videoPreference: cameras[1].deviceId,
  parameters: parameters,
});

Participant Management Methods

// Get all participants
const allParticipants = parameters.participants;
console.log('Total participants:', parameters.participantsCounter);

// Get participants by role
const hosts = parameters.participants.filter(p => p.islevel === '2');
const moderators = parameters.participants.filter(p => p.islevel === '1');

// Remove participant (host only)
if (parameters.islevel === '2') {
  await parameters.removeParticipants({
    participant: { id: 'participant-id', name: 'John Doe' },
    parameters: parameters,
  });
}

// Send direct message to participant
await parameters.sendMessage({
  message: 'Hello!',
  receivers: ['participant-id'],
  type: 'direct',
  parameters: parameters,
});

Chat & Messaging Methods

// Send message to everyone
await parameters.sendMessage({
  message: 'Hello everyone!',
  type: 'chat',
  receivers: [],
  parameters: parameters,
});

// Send direct message
await parameters.sendMessage({
  message: 'Hi John!',
  type: 'direct',
  receivers: ['participant-id'],
  parameters: parameters,
});

// Access message history
const allMessages = parameters.messages;
const unreadCount = parameters.unreadMessageCount;

Recording Methods

// Start recording (host only)
if (parameters.islevel === '2') {
  await parameters.startRecording({
    parameters: parameters,
  });
}

// Pause recording
await parameters.pauseRecording({
  parameters: parameters,
});

// Resume recording
await parameters.resumeRecording({
  parameters: parameters,
});

// Stop recording
await parameters.stopRecording({
  parameters: parameters,
});

// Configure recording settings
await parameters.updateRecordingMediaOptions('video');
await parameters.updateRecordingVideoOptions('all');

Polls & Survey Methods

// Create a poll (host only)
if (parameters.islevel === '2') {
  await parameters.handleCreatePoll({
    poll: {
      question: 'Should we take a break?',
      type: 'yesNo',
      options: ['Yes', 'No'],
    },
    parameters: parameters,
  });
}

// Vote on a poll
await parameters.handleVotePoll({
  pollId: 'poll-123',
  choice: 'Yes',
  parameters: parameters,
});

// End a poll (host only)
await parameters.handleEndPoll({
  pollId: 'poll-123',
  parameters: parameters,
});

// Access poll data
const allPolls = parameters.polls;
const activePolls = allPolls.filter(p => p.status === 'active');

Breakout Room Methods

// Launch breakout rooms interface (host only)
if (parameters.islevel === '2') {
  await parameters.launchBreakoutRooms({
    parameters: parameters,
  });
}

// Access breakout room data
const breakoutRooms = parameters.breakoutRooms;
const currentRoom = parameters.currentBreakoutRoom;

// Check if user is in a breakout room
const isInBreakoutRoom = currentRoom !== null;

Advanced Customization & Styling

Custom Pre-Join Screen

Create a completely custom pre-join experience:

import React, { useState } from 'react';
import { View, Text, TextInput, TouchableOpacity, StyleSheet } from 'react-native';
import { MediasfuGeneric } from 'mediasfu-reactnative';

function CustomPreJoinScreen({ onJoin }) {
  const [userName, setUserName] = useState('');
  const [roomName, setRoomName] = useState('');

  const handleJoin = () => {
    if (userName.trim() && roomName.trim()) {
      onJoin({ userName: userName.trim(), roomName: roomName.trim() });
    }
  };

  return (
    <View style={styles.container}>
      <Text style={styles.title}>Join a Meeting</Text>
      
      <TextInput
        style={styles.input}
        placeholder="Your Name"
        value={userName}
        onChangeText={setUserName}
      />
      
      <TextInput
        style={styles.input}
        placeholder="Room Name"
        value={roomName}
        onChangeText={setRoomName}
      />

      <TouchableOpacity style={styles.joinButton} onPress={handleJoin}>
        <Text style={styles.joinButtonText}>Join Meeting</Text>
      </TouchableOpacity>
    </View>
  );
}

function App() {
  const [showMeeting, setShowMeeting] = useState(false);
  const [meetingConfig, setMeetingConfig] = useState(null);

  const handleJoin = (config) => {
    setMeetingConfig(config);
    setShowMeeting(true);
  };

  if (!showMeeting) {
    return <CustomPreJoinScreen onJoin={handleJoin} />;
  }

  return (
    <MediasfuGeneric
      credentials={{ apiUserName: 'your_username', apiKey: 'your_api_key' }}
      noUIPreJoinOptions={{
        action: 'create',
        userName: meetingConfig.userName,
        capacity: 50,
        duration: 30,
        eventType: 'conference',
      }}
    />
  );
}

const styles = StyleSheet.create({
  container: { flex: 1, padding: 20, justifyContent: 'center' },
  title: { fontSize: 28, fontWeight: 'bold', marginBottom: 30, textAlign: 'center' },
  input: { padding: 15, borderRadius: 8, marginBottom: 15, backgroundColor: '#f0f0f0' },
  joinButton: { backgroundColor: '#4CAF50', padding: 18, borderRadius: 8, alignItems: 'center' },
  joinButtonText: { color: 'white', fontSize: 18, fontWeight: 'bold' },
});

export default App;

Understanding Data Structures

Participant Object

{
  id: 'participant-id-123',
  name: 'John Doe',
  islevel: '2',              // '0'=participant, '1'=co-host, '2'=host
  muted: false,
  videoOn: true,
  isScreenShare: false,
}

Message Object

{
  sender: 'John Doe',
  receivers: ['Jane Doe'],
  message: 'Hello!',
  timestamp: 1696118400000,
  group: true,
}

Poll Object

{
  id: 'poll-123',
  question: 'Should we take a break?',
  type: 'yesNo',
  options: ['Yes', 'No'],
  votes: [5, 3],
  status: 'active',
}

Troubleshooting & Best Practices

Common Issues and Solutions

Issue: Video not displaying on Android

Solution: Ensure proper permissions in AndroidManifest.xml:

<uses-permission android:name="android.permission.CAMERA" />
<uses-permission android:name="android.permission.RECORD_AUDIO" />

Request permissions at runtime:

import { PermissionsAndroid, Platform } from 'react-native';

async function requestPermissions() {
  if (Platform.OS === 'android') {
    await PermissionsAndroid.requestMultiple([
      PermissionsAndroid.PERMISSIONS.CAMERA,
      PermissionsAndroid.PERMISSIONS.RECORD_AUDIO,
    ]);
  }
}

Best Practices

Always request permissions before accessing camera/microphone
Check device availability before switching devices
Handle errors gracefully with try-catch blocks
Lazy load modals to improve performance
Test on real devices - emulators have limited media support


Quick Reference: Complete Method List

Media Control

  • clickVideo() - Toggle video
  • clickAudio() - Toggle audio
  • clickScreenShare() - Toggle screen sharing
  • switchVideoAlt() - Switch camera
  • switchUserVideo() - Switch to specific camera
  • switchUserAudio() - Switch microphone

Device Management

  • getMediaDevicesList() - Get available devices
  • checkPermission() - Check permissions

Participant Management

  • muteParticipants() - Mute participant
  • removeParticipants() - Remove participant
  • messageParticipants() - Message participant

Recording

  • startRecording() - Start recording
  • pauseRecording() - Pause recording
  • resumeRecording() - Resume recording
  • stopRecording() - Stop recording

Chat & Messaging

  • sendMessage() - Send message
  • updateMessages() - Update message list

Polls

  • handleCreatePoll() - Create poll
  • handleVotePoll() - Vote on poll
  • handleEndPoll() - End poll

Breakout Rooms

  • launchBreakoutRooms() - Open breakout rooms
  • updateBreakoutRooms() - Update rooms
  • returnToMainRoom() - Exit breakout room

This comprehensive guide covers the essential aspects of MediaSFU React Native SDK. For additional details, visit the full API documentation.


Basic Usage Guide

A basic guide on how to use the module for common tasks.

This section will guide users through the initial setup and installation of the npm module.

This guide provides a basic overview of how to set up and use the mediasfu-reactnative module for common tasks across platforms.

Initial Setup and Installation

To get started with mediasfu-reactnative, follow the instructions below. This module is optimized for use with Non-Expo dependencies, making it ideal for projects that require seamless deployment across web and mobile platforms.

Note: If you are integrating into a React Native Expo app, the best option is to use the core mediasfu-reactnative-expo package, which you can find on npm at mediasfu-reactnative-expo.

Introduction

MediaSFU is a 2-page application consisting of a prejoin/welcome page and the main events room page. This guide will walk you through the basic usage of the module for setting up these pages.

Documentation Reference

For comprehensive documentation on the available methods, components, and functions, please visit mediasfu.com. This resource provides detailed information for this guide and additional documentation.

Prebuilt Event Rooms

MediaSFU provides prebuilt event rooms for various purposes. These rooms are rendered as full pages and can be easily imported and used in your application. Here are the available prebuilt event rooms:

  1. MediasfuGeneric: A generic event room suitable for various types of events.
  2. MediasfuBroadcast: A room optimized for broadcasting events.
  3. MediasfuWebinar: Specifically designed for hosting webinars.
  4. MediasfuConference: Ideal for hosting conferences.
  5. MediasfuChat: A room tailored for interactive chat sessions.

Users can easily pick an interface and render it in their app.

If no API credentials are provided, a default home page will be displayed where users can scan or manually enter the event details.

To use these prebuilt event rooms, simply import them into your application:

import { MediasfuGeneric, MediasfuBroadcast, MediasfuWebinar, MediasfuConference, MediasfuChat } from 'mediasfu-reactnative';

Simplest Usage

The simplest way to use MediaSFU is by directly rendering a prebuilt event room component, such as MediasfuGeneric:

import { MediasfuGeneric } from 'mediasfu-reactnative';

const App = () => {
  return (
    <MediasfuGeneric />
  );
}

export default App;

Programmatically Fetching Tokens

If you prefer to fetch the required tokens programmatically without visiting MediaSFU's website, you can use the PreJoinPage component and pass your credentials as props:

import { MediasfuGeneric, PreJoinPage } from 'mediasfu-reactnative';

const App = () => {
  const credentials = { apiUserName: "yourAPIUserName", apiKey: "yourAPIKey" };

  return (
    <MediasfuGeneric PrejoinPage={PreJoinPage} credentials={credentials} />
  );
}

export default App;

Preview of Welcome Page

 

Preview of Prejoin Page

Custom Welcome/Prejoin Page

Alternatively, you can design your own welcome/prejoin page. The core function of this page is to fetch user tokens from MediaSFU's API and establish a connection with the returned link if valid.

Parameters Passed to Custom Page

MediaSFU passes relevant parameters to the custom welcome/prejoin page:

let { showAlert, updateIsLoadingModalVisible, connectSocket, updateSocket, updateValidated,
     updateApiUserName, updateApiToken, updateLink, updateRoomName, updateMember } = parameters;

Ensure that your custom page implements the following updates:

updateSocket(socket);
updateApiUserName(apiUserName);
updateApiToken(apiToken);
updateLink(link);
updateRoomName(apiUserName);
updateMember(userName);
updateValidated(true);

See the following code for the PreJoinPage page logic:

import React, { useState, useEffect, useRef } from 'react';
import {
  View,
  Text,
  TextInput,
  Pressable,
  Image,
  StyleSheet,
  ScrollView,
  KeyboardAvoidingView,
  Platform,
} from 'react-native';
import Orientation from 'react-native-orientation-locker';
import { Socket } from 'socket.io-client';
import {
  ConnectSocketType,
  ShowAlert,
  ConnectLocalSocketType,
  ResponseLocalConnection,
  ResponseLocalConnectionData,
  RecordingParams,
  MeetingRoomParams,
  CreateMediaSFURoomOptions,
  JoinMediaSFURoomOptions,
} from '../../@types/types';
import RNPickerSelect from 'react-native-picker-select';
import { checkLimitsAndMakeRequest } from '../../methods/utils/checkLimitsAndMakeRequest';
import { createRoomOnMediaSFU } from '../../methods/utils/createRoomOnMediaSFU';
import { CreateRoomOnMediaSFUType, JoinRoomOnMediaSFUType, joinRoomOnMediaSFU } from '../../methods/utils/joinRoomOnMediaSFU';

/**
 * Interface defining the parameters for joining a local event room.
 */
export interface JoinLocalEventRoomParameters {
  eventID: string;
  userName: string;
  secureCode?: string;
  videoPreference?: string | null;
  audioPreference?: string | null;
  audioOutputPreference?: string | null;
}

/**
 * Interface defining the options for joining a local event room.
 */
export interface JoinLocalEventRoomOptions {
  joinData: JoinLocalEventRoomParameters;
  link?: string;
}

/**
 * Interface defining the response structure when creating or joining a local room.
 */
export interface CreateLocalRoomParameters {
  eventID: string;
  duration: number;
  capacity: number;
  userName: string;
  scheduledDate: Date;
  secureCode: string;
  waitRoom?: boolean;
  recordingParams?: RecordingParams;
  eventRoomParams?: MeetingRoomParams;
  videoPreference?: string | null;
  audioPreference?: string | null;
  audioOutputPreference?: string | null;
  mediasfuURL?: string;
}

/**
 * Interface defining the response structure when joining a local room.