Wojciech Brożonowicz
Wojciech Brożonowicz
~1 min read

Categories

Tags

React app - how to use webcam

To use camera in web React app in class component, first install react-webcam:

npm install react-webcam

Then follow these steps:

1] import webcam module

import Webcam from "react-webcam";

2] define state (We need 2 objects: imgSrc - it will be base64 image string, webcamRef - ref to device webcam)

state = {
		imgSrc:null,
		webcamRef: null,
	}

3] define function to set webcamRef

setRef = (webcam) => {
		this.webcam = webcam;
	  };

4] define function to capture image

capture = () => {
		const imageSrc = this.webcam.getScreenshot();
		this.setState({imgSrc: imageSrc})
	 };

5] render our Webcam component with button to capture

<Webcam
      audio={false}
    	ref={this.setRef}
      screenshotFormat="image/jpeg"
      />
      <button onClick={this.capture}>Capture photo</button>
      
      // below code to render captured image
        {<img
          src={this.state.imgSrc}
        />}
      

That’s all!

Some other options - check docs: https://www.npmjs.com/package/react-webcam