react-webcam-torch
v1.0.0
Published
A React webcam component with torch/flashlight support, extending react-webcam
Maintainers
Readme
React Webcam Torch# React + TypeScript + Vite
A React webcam component with torch/flashlight support, extending react-webcam.This template provides a minimal setup to get React working in Vite with HMR and some ESLint rules.
This package inherits all properties from react-webcam and adds the ability to control the device's torch (flashlight) when available.Currently, two official plugins are available:
Features- @vitejs/plugin-react uses Babel (or oxc when used in rolldown-vite) for Fast Refresh
@vitejs/plugin-react-swc uses SWC for Fast Refresh
✅ All features from
react-webcam🔦 Torch/flashlight control## React Compiler
📱 Mobile device support (rear cameras)
🎯 TypeScript supportThe React Compiler is not enabled on this template because of its impact on dev & build performances. To add it, see this documentation.
🔄 Automatic torch capability detection
🎨 Same API as react-webcam with additional torch props## Expanding the ESLint configuration
InstallationIf you are developing a production application, we recommend updating the configuration to enable type-aware lint rules:
bashjs
npm install react-webcam-torchexport default defineConfig([
or globalIgnores(['dist']),
yarn add react-webcam-torch {
or files: ['**/*.{ts,tsx}'],
pnpm add react-webcam-torch extends: [
## Usage // Remove tseslint.configs.recommended and replace with this
tseslint.configs.recommendedTypeChecked,
### Basic Usage // Alternatively, use this for stricter rules
tseslint.configs.strictTypeChecked,
```tsx // Optionally, add this for stylistic rules
import { WebcamWithTorch } from 'react-webcam-torch'; tseslint.configs.stylisticTypeChecked,
function App() { // Other configs...
const [torchEnabled, setTorchEnabled] = React.useState(false); ],
languageOptions: {
return ( parserOptions: {
<div> project: ['./tsconfig.node.json', './tsconfig.app.json'],
<WebcamWithTorch tsconfigRootDir: import.meta.dirname,
torch={torchEnabled} },
onTorchCapabilityChange={(supported) => { // other options...
console.log('Torch supported:', supported); },
}} },
onTorchChange={(enabled) => {])
console.log('Torch state:', enabled);```
}}
/>You can also install [eslint-plugin-react-x](https://github.com/Rel1cx/eslint-react/tree/main/packages/plugins/eslint-plugin-react-x) and [eslint-plugin-react-dom](https://github.com/Rel1cx/eslint-react/tree/main/packages/plugins/eslint-plugin-react-dom) for React-specific lint rules:
<button onClick={() => setTorchEnabled(!torchEnabled)}>
Toggle Torch```js
</button>// eslint.config.js
</div>import reactX from 'eslint-plugin-react-x'
);import reactDom from 'eslint-plugin-react-dom'
}
```export default defineConfig([
globalIgnores(['dist']),
### Advanced Usage with Ref {
files: ['**/*.{ts,tsx}'],
```tsx extends: [
import { useRef } from 'react'; // Other configs...
import { WebcamWithTorch, WebcamWithTorchRef } from 'react-webcam-torch'; // Enable lint rules for React
reactX.configs['recommended-typescript'],
function App() { // Enable lint rules for React DOM
const webcamRef = useRef<WebcamWithTorchRef>(null); reactDom.configs.recommended,
],
const handleToggleTorch = async () => { languageOptions: {
if (webcamRef.current) { parserOptions: {
const newState = await webcamRef.current.toggleTorch(); project: ['./tsconfig.node.json', './tsconfig.app.json'],
console.log('Torch is now:', newState); tsconfigRootDir: import.meta.dirname,
} },
}; // other options...
},
const handleCheckSupport = () => { },
if (webcamRef.current) {])
const supported = webcamRef.current.getTorchSupported();```
console.log('Torch supported:', supported);
}
};
const capturePhoto = () => {
if (webcamRef.current) {
const imageSrc = webcamRef.current.getScreenshot();
console.log('Captured:', imageSrc);
}
};
return (
<div>
<WebcamWithTorch ref={webcamRef} />
<button onClick={handleToggleTorch}>Toggle Torch</button>
<button onClick={handleCheckSupport}>Check Support</button>
<button onClick={capturePhoto}>Capture Photo</button>
</div>
);
}With Specific Camera Constraints
import { WebcamWithTorch } from 'react-webcam-torch';
function App() {
const [torchEnabled, setTorchEnabled] = React.useState(false);
return (
<WebcamWithTorch
torch={torchEnabled}
videoConstraints={{
facingMode: 'environment', // Use rear camera
width: 1920,
height: 1080,
}}
onUserMediaError={(error) => {
console.error('Camera error:', error);
}}
/>
);
}API
Props
WebcamWithTorch accepts all props from react-webcam plus the following:
| Prop | Type | Default | Description |
|------|------|---------|-------------|
| torch | boolean | false | Enable or disable the torch/flashlight |
| onTorchChange | (enabled: boolean) => void | - | Callback when torch state changes |
| onTorchCapabilityChange | (supported: boolean) => void | - | Callback when torch capability is detected |
Ref Methods
In addition to all methods from react-webcam, the ref provides:
| Method | Returns | Description |
|--------|---------|-------------|
| getTorchSupported() | boolean | Check if torch is supported on current device |
| toggleTorch() | Promise<boolean> | Toggle torch and return new state |
All other methods from react-webcam are available:
getScreenshot()getCanvas()stream(property)
Browser Support
The torch feature relies on the MediaStream Image Capture API and specifically the torch constraint.
Supported:
- Chrome/Edge on Android (with rear camera)
- Safari on iOS (limited support)
Not Supported:
- Desktop browsers (cameras don't have torch)
- Front-facing mobile cameras
- Some older mobile devices
The component will gracefully handle unsupported devices - the torch prop will simply have no effect, and getTorchSupported() will return false.
Important Notes
Camera Selection: Torch is typically only available on rear-facing cameras. Use
videoConstraints={{ facingMode: 'environment' }}to request the rear camera.Permissions: The camera permission must be granted before torch can be controlled.
Device Capability: Not all devices support torch control. Always check
getTorchSupported()or use theonTorchCapabilityChangecallback.Battery Impact: Keeping the torch on can drain battery quickly. Consider implementing auto-off functionality.
Example: QR Code Scanner with Torch
import { useRef, useState } from 'react';
import { WebcamWithTorch, WebcamWithTorchRef } from 'react-webcam-torch';
function QRScanner() {
const webcamRef = useRef<WebcamWithTorchRef>(null);
const [torchEnabled, setTorchEnabled] = useState(false);
const [torchSupported, setTorchSupported] = useState(false);
return (
<div className="scanner">
<WebcamWithTorch
ref={webcamRef}
torch={torchEnabled}
videoConstraints={{
facingMode: 'environment',
}}
onTorchCapabilityChange={setTorchSupported}
screenshotFormat="image/jpeg"
/>
{torchSupported && (
<button onClick={() => setTorchEnabled(!torchEnabled)}>
{torchEnabled ? '🔦 Turn Off' : '🔦 Turn On'}
</button>
)}
</div>
);
}Development
# Install dependencies
npm install
# Run dev server
npm run dev
# Build library
npm run build
# Lint
npm run lintLicense
MIT
Credits
This package extends react-webcam by mozmorris.
