Use Webcam with React easily

0xkoji - Jul 29 '21 - - Dev Community

Step1 Create a react app with create-react-app

$ yarn create react-app webcam-app --template typescript
Enter fullscreen mode Exit fullscreen mode

Step2 Install react-webcam (@types/react-webcam)

GitHub logo mozmorris / react-webcam

Webcam component

react-webcam

Build Status downloads

DEMO: https://codepen.io/mozmorris/pen/JLZdoP

https://www.npmjs.com/package/react-webcam

Webcam component for React. See http://caniuse.com/#feat=stream for browser compatibility.

Note: Browsers will throw an error if the page is loaded from insecure origin. I.e. Use https.

Installation

# with npm
npm install react-webcam

# with yarn
yarn add react-webcam
Enter fullscreen mode Exit fullscreen mode

Demo

https://codepen.io/mozmorris/pen/JLZdoP

Usage

import React from "react";
import Webcam from "react-webcam";

const WebcamComponent = () => <Webcam />;
Enter fullscreen mode Exit fullscreen mode

Props

The props here are specific to this component but one can pass any prop to the underlying video tag eg className, style, muted, etc

prop type default notes
audio boolean false enable/disable audio
audioConstraints object MediaStreamConstraint(s) for the audio
disablePictureInPicture boolean false disable Picture-in-Picture
forceScreenshotSourceSize boolean false uses size of underlying source video stream (and thus ignores other size related props)
imageSmoothing boolean true pixel smoothing of the screenshot taken
mirrored boolean false show camera preview and get the

$ yarn add react-webcam @types/react-webcam
Enter fullscreen mode Exit fullscreen mode

Step3 Create a simple component

src/components/WebCamDisplay/index.tsx

import { useRef } from "react";
import Webcam from "react-webcam";

export const WebCamDisplay = () => {
  const webcam = useRef<Webcam>(null);

  return (
    <>
      <Webcam audio={false} ref={webcam} />
    </>
  );
};

Enter fullscreen mode Exit fullscreen mode
$ yarn start
Enter fullscreen mode Exit fullscreen mode

Codesandbox
https://codesandbox.io/s/agitated-stonebraker-h11sl?file=/src/components/WebCamDisplay/index.tsx

. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .