@webrtc2/client
Version:
WebRTC2 Client - React Native, Web & Electron WebRTC hooks and components for cross-platform real-time video calls, audio communication, and screen sharing
351 lines (285 loc) • 8.73 kB
Markdown
# @webrtc2/client - Cross-Platform WebRTC React Hooks & Components
[](https://www.npmjs.com/package/@webrtc2/client)
[](https://typescriptlang.org/)
[](https://reactnative.dev/)
[](https://electronjs.org/)
**React hooks and components for WebRTC cross-platform real-time communication** - Build video calls, audio chat, and screen sharing across React Native, Web browsers, and Electron desktop apps.
## 🚀 WebRTC Made Simple for React Developers
@webrtc2/client solves the complexity of WebRTC integration in React applications by providing:
- **🎯 React Hooks**: `useWebRTC`, `useMediaStream`, `usePeerConnection`
- **📱 Cross-Platform**: React Native iOS/Android, Web browsers, Electron desktop
- **🔧 TypeScript**: Full type safety and IntelliSense support
- **⚡ Zero Config**: Works out-of-the-box with sensible defaults
- **🎥 Media Controls**: Camera, microphone, screen sharing APIs
## 📦 Installation
```bash
# npm
npm install @webrtc2/client
# yarn
yarn add @webrtc2/client
# pnpm
pnpm add @webrtc2/client
```
### Platform-Specific Setup
#### React Native WebRTC
```bash
npm install react-native-webrtc
# iOS: Add camera/microphone permissions to Info.plist
# Android: Add permissions to AndroidManifest.xml
```
#### Electron WebRTC
```bash
npm install electron
# WebRTC works natively in Electron's Chromium engine
```
## 🎯 Quick Start Examples
### Basic Video Call Hook
```tsx
import { useWebRTC } from '@webrtc2/client';
function VideoCallComponent() {
const {
localStream,
remoteStream,
connectionState,
connect,
disconnect,
error
} = useWebRTC({
iceServers: [{ urls: 'stun:stun.l.google.com:19302' }]
});
return (
<div className="video-call">
{/* Local video stream */}
<video
ref={video => video && (video.srcObject = localStream)}
autoPlay
muted
playsInline
/>
{/* Remote video stream */}
<video
ref={video => video && (video.srcObject = remoteStream)}
autoPlay
playsInline
/>
{/* Connection controls */}
<div className="controls">
<button onClick={() => connect('room-123')}>
Join Call
</button>
<button onClick={disconnect}>
Leave Call
</button>
<p>Status: {connectionState}</p>
</div>
</div>
);
}
```
### React Native Video Call
```tsx
import React from 'react';
import { View, TouchableOpacity, Text } from 'react-native';
import { RTCView } from 'react-native-webrtc';
import { useWebRTC } from '@webrtc2/client';
function ReactNativeVideoCall() {
const { localStream, remoteStream, connect, connectionState } = useWebRTC();
return (
<View style={{ flex: 1 }}>
{/* Local video */}
<RTCView
streamURL={localStream?.toURL()}
style={{ flex: 1 }}
mirror={true}
/>
{/* Remote video */}
<RTCView
streamURL={remoteStream?.toURL()}
style={{ flex: 1 }}
/>
{/* Controls */}
<TouchableOpacity
onPress={() => connect('mobile-room')}
style={{ padding: 20, backgroundColor: '#007AFF' }}
>
<Text style={{ color: 'white', textAlign: 'center' }}>
Join WebRTC Call
</Text>
</TouchableOpacity>
</View>
);
}
```
### WebRTC Provider Setup
```tsx
import { WebRTCProvider } from '@webrtc2/client';
function App() {
return (
<WebRTCProvider
config={{
iceServers: [
{ urls: 'stun:stun.l.google.com:19302' },
{
urls: 'turn:your-turn-server.com:3478',
username: 'user',
credential: 'pass'
}
]
}}
>
<VideoCallComponent />
</WebRTCProvider>
);
}
```
## 🎛️ Advanced WebRTC Features
### Screen Sharing Hook
```tsx
import { useScreenShare } from '@webrtc2/client';
function ScreenShareComponent() {
const {
screenStream,
isSharing,
startScreenShare,
stopScreenShare,
error
} = useScreenShare();
return (
<div>
<video
ref={video => video && (video.srcObject = screenStream)}
autoPlay
playsInline
/>
<button onClick={isSharing ? stopScreenShare : startScreenShare}>
{isSharing ? 'Stop Sharing' : 'Share Screen'}
</button>
</div>
);
}
```
### Media Device Controls
```tsx
import { useMediaDevices } from '@webrtc2/client';
function MediaControls() {
const {
devices,
selectedCamera,
selectedMicrophone,
switchCamera,
switchMicrophone,
toggleCamera,
toggleMicrophone,
isCameraEnabled,
isMicrophoneEnabled
} = useMediaDevices();
return (
<div className="media-controls">
{/* Camera controls */}
<select onChange={e => switchCamera(e.target.value)}>
{devices.cameras.map(camera => (
<option key={camera.deviceId} value={camera.deviceId}>
{camera.label}
</option>
))}
</select>
<button onClick={toggleCamera}>
{isCameraEnabled ? '📷' : '📷❌'}
</button>
{/* Microphone controls */}
<button onClick={toggleMicrophone}>
{isMicrophoneEnabled ? '🎤' : '🎤❌'}
</button>
</div>
);
}
```
### Peer Connection Stats
```tsx
import { usePeerConnectionStats } from '@webrtc2/client';
function ConnectionStats() {
const { stats, isConnected, latency, bitrate, packetLoss } = usePeerConnectionStats();
return (
<div className="connection-stats">
<p>Status: {isConnected ? '🟢 Connected' : '🔴 Disconnected'}</p>
<p>Latency: {latency}ms</p>
<p>Bitrate: {bitrate} kbps</p>
<p>Packet Loss: {packetLoss}%</p>
</div>
);
}
```
## 🔧 API Reference
### useWebRTC Hook
```tsx
const {
localStream, // Local media stream
remoteStream, // Remote media stream
connectionState, // 'connecting' | 'connected' | 'disconnected' | 'failed'
connect, // (roomId: string) => Promise<void>
disconnect, // () => void
error, // Error | null
isConnected, // boolean
participants // Participant[]
} = useWebRTC(config);
```
### WebRTCProvider Props
```tsx
interface WebRTCConfig {
iceServers: RTCIceServer[];
signalingUrl?: string;
autoConnect?: boolean;
enableVideo?: boolean;
enableAudio?: boolean;
videoConstraints?: MediaTrackConstraints;
audioConstraints?: MediaTrackConstraints;
}
```
## 🌐 Cross-Platform Compatibility
| Feature | Web Browser | React Native | Electron |
|---------|-------------|--------------|----------|
| Video Calls | ✅ All modern browsers | ✅ iOS/Android | ✅ Desktop |
| Audio Calls | ✅ WebRTC API | ✅ Native | ✅ Chromium |
| Screen Share | ✅ getDisplayMedia | ✅ iOS 12+ | ✅ Built-in |
| File Transfer | ✅ DataChannel | ✅ Custom | ✅ Node.js |
| Background Mode | ⚠️ Limited | ✅ Native | ✅ Always |
## 🐛 Troubleshooting WebRTC Issues
### Common Problems & Solutions
#### Camera/Microphone Permission Denied
```tsx
// Handle permission errors
const { error } = useWebRTC();
if (error?.name === 'NotAllowedError') {
return <div>Please allow camera/microphone access</div>;
}
```
#### ICE Connection Failed
```tsx
// Add TURN servers for NAT traversal
const config = {
iceServers: [
{ urls: 'stun:stun.l.google.com:19302' },
{
urls: 'turn:your-turn-server.com:3478',
username: 'user',
credential: 'password'
}
]
};
```
#### React Native iOS Simulator Issues
```tsx
// iOS Simulator doesn't support camera
// Test on real device or use mock streams
```
## 📚 Related Packages
- [@webrtc2/peer](../peer) - Low-level WebRTC peer connection management
- [@webrtc2/types](../types) - TypeScript definitions for WebRTC
- [@webrtc2/utils](../utils) - WebRTC utility functions
- [@webrtc2/config](../config) - Configuration management
## 🤝 Contributing
We welcome contributions! Please see our [Contributing Guide](../../CONTRIBUTING.md) for details.
## 📄 License
MIT License - see [LICENSE](../../LICENSE) for details.
---
**Keywords**: WebRTC React hooks, React Native WebRTC, Electron WebRTC, cross-platform video calls, WebRTC components, React WebRTC client, TypeScript WebRTC, real-time communication React, peer-to-peer React, WebRTC screen sharing, video chat React, audio calls React