DEV Community

Saba beigi
Saba beigi

Posted on

react-webcam + TypeScript

react-webcam allows you to implement camera shooting functionality in your React app.

Click [Start] in the above demo to start the camera. If you are asked for camera shooting permission, please allow it. (We do not send the captured data to the outside)

Then the image captured by the camera is displayed. Also, [Exit] on the upper left is the end of camera shooting, and [Capture] on the lower left is the button to capture the captured image.

Then the image captured by the camera is displayed. Also, [Exit] on the upper left is the button to end the camera shooting, and [Capture] on the lower left is the button to capture the captured video.

When capturing, the capture of the captured video was displayed.

import { useRef, useState, useCallback } from "react";
import Webcam from "react-webcam";
import "./styles.css";

const videoConstraints = {
  width: 720,
  height: 360,
  facingMode: "user"
};

export const App = () => {
  const [isCaptureEnable, setCaptureEnable] = useState<boolean>(false);
  const webcamRef = useRef<Webcam>(null);
  const [url, setUrl] = useState<string | null>(null);
  const capture = useCallback(() => {
    const imageSrc = webcamRef.current?.getScreenshot();
    if (imageSrc) {
      setUrl(imageSrc);
    }
  }, [webcamRef]);

  return (
    <>
      <header>
        <h1>camera app</h1>
      </header>
      {isCaptureEnable || (
        <button onClick={() => setCaptureEnable(true)}>start</button>
      )}
      {isCaptureEnable && (
        <>
          <div>
            <button onClick={() => setCaptureEnable(false)}>end </button>
          </div>
          <div>
            <Webcam
              audio={false}
              width={540}
              height={360}
              ref={webcamRef}
              screenshotFormat="image/jpeg"
              videoConstraints={videoConstraints}
            />
          </div>
          <button onClick={capture}>capture</button>
        </>
      )}
      {url && (
        <>
          <div>
            <button
              onClick={() => {
                setUrl(null);
              }}
            >
              delete
            </button>
          </div>
          <div>
            <img src={url} alt="Screenshot" />
          </div>
        </>
      )}
    </>
  );
};

Enter fullscreen mode Exit fullscreen mode
  • getScreenshot():You can use the Webcam imported by import Webcam from "react-webcam" for the type of still image data acquired by

  • getScreenshot():The still image data obtained by can be displayed on the screen by specifying it as it is in the src property.

Oldest comments (2)

Collapse
 
markrufino profile image
markr

I rarely sign up on sites to comment, but I really wanted to thank you for this! It helped me work around a lint / type related problem that I can't figure out.

Collapse
 
sababg profile image
Saba beigi

thanks, it makes me happy