React Webcam Component

7.2.0 · active · verified Tue Apr 21

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

Warnings

Install

Imports

Quickstart

Demonstrates how to integrate the Webcam component, configure video constraints, and capture a screenshot, handling potential errors.

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;

view raw JSON →