React Webcam Component
react-webcam is a React component designed to streamline the integration of webcam functionality into web applications. As of its latest stable release, version 7.2.0 (published approximately two years ago), it provides a declarative API for accessing the user's camera, displaying the video stream, and capturing still images. It abstracts away the complexities of the underlying MediaDevices.getUserMedia() API, handling permissions, stream management, and rendering the video feed within a standard React component lifecycle. Key differentiators include its straightforward prop interface for controlling audio, video constraints, and screenshot behavior, as well as a dedicated method (`getScreenshot`) for capturing images in various formats and qualities. While the npm package hasn't seen a recent major release, its GitHub repository shows ongoing activity in issues, suggesting continued maintenance. It fully supports TypeScript, enhancing developer experience with type safety. The component is particularly useful for applications requiring photo capture, video previews, or integration with image processing libraries.
Common errors
-
NotAllowedError: Permission denied
cause The user denied webcam access permission or the page is not served over HTTPS.fixPrompt the user to grant camera permissions and ensure the application is running on a secure origin (HTTPS or localhost). -
TypeError: Cannot read properties of undefined (reading 'getScreenshot')
cause Attempting to call `getScreenshot` on a `webcamRef.current` that is `null` or `undefined` because the Webcam component hasn't rendered or mounted yet.fixEnsure the `webcamRef.current` exists before calling `getScreenshot`. This often means checking `if (webcamRef.current)` before accessing its methods. -
MediaStreamError: Only secure origins are allowed.
cause The browser's `getUserMedia` API was invoked from an insecure origin (HTTP instead of HTTPS).fixServe your application over HTTPS. For local development, use `https://localhost`. -
Webcam showing blank screen
cause This can be due to various reasons: permission denied, no camera detected, incorrect video constraints, or browser compatibility issues.fixCheck browser console for `MediaStreamError` messages. Verify camera is connected and not in use by another application. Review `videoConstraints` for validity and ensure HTTPS is used. Implement `onUserMediaError` to debug specific errors.
Warnings
- breaking Accessing the webcam via `getUserMedia` (which react-webcam uses) is restricted to secure contexts (HTTPS or localhost). Browsers will throw a `NotAllowedError` or `SecurityError` if the page is loaded over HTTP.
- gotcha The `getScreenshot` method should only be called once the webcam stream is active and the component's `ref` is populated. Calling it too early can lead to `null` or `undefined` issues, or an empty screenshot.
- gotcha Webcam access requires explicit user permission. If the user denies permission, `onUserMediaError` will be called with a `MediaStreamError`, and the webcam stream will not activate, resulting in a blank video area.
- gotcha The `forceScreenshotSourceSize` prop, when true, forces `getScreenshot` to use the dimensions of the underlying video stream, potentially overriding `minScreenshotHeight`/`minScreenshotWidth` or dimensions passed directly to `getScreenshot`.
Install
-
npm install react-webcam -
yarn add react-webcam -
pnpm add react-webcam
Imports
- Webcam
import { Webcam } from 'react-webcam';import Webcam from 'react-webcam';
- WebcamProps
import { WebcamProps } from 'react-webcam';import type { WebcamProps } from 'react-webcam'; - Webcam (CJS)
const Webcam = require('react-webcam');const Webcam = require('react-webcam').default;
Quickstart
import React, { useRef, useState, useCallback } from 'react';
import Webcam from 'react-webcam';
const videoConstraints = {
width: 1280,
height: 720,
facingMode: 'user',
};
const WebcamCapture = () => {
const webcamRef = useRef(null);
const [imageSrc, setImageSrc] = useState(null);
const capture = useCallback(() => {
if (webcamRef.current) {
const screenshot = webcamRef.current.getScreenshot();
setImageSrc(screenshot);
console.log('Screenshot captured:', screenshot ? 'Yes' : 'No');
}
}, [webcamRef]);
return (
<div className="webcam-container">
<Webcam
audio={false}
ref={webcamRef}
screenshotFormat="image/jpeg"
width={640}
height={360}
videoConstraints={videoConstraints}
onUserMediaError={(error) => console.error('Webcam error:', error)}
/>
<button onClick={capture}>Capture photo</button>
{imageSrc && (
<div>
<h3>Captured Image:</h3>
<img src={imageSrc} alt="webcam-screenshot" />
</div>
)}
</div>
);
};
export default WebcamCapture;