How to capture image in React JS with React-webcam (Demo)

 import React, { useState, useRef } from "react";
    import Webcam from "react-webcam";
    
    function Selfie() {
      const webcamRef = useRef(null);
      const [imgSrc, setImgSrc] = useState("");
    
      const capture = () => {
        const imageSrc = webcamRef.current.getScreenshot();
        setImgSrc(imageSrc);
        // Store Selfie in Localstorage
        localStorage.setItem("selfie", imageSrc);
      }
    
      return (
          <React.Fragment>
            {imgSrc ? 
            <>
                <img src={imgSrc} alt="Selfie"/>
                <button onClick={() => {
                    setImgSrc("");
                    localStorage.removeItem("selfie");
                }} className="button"><span>Retake Photo </span></button>
            </>
            :
            <>
                <div className="camera-container">
                    <Webcam
                    audio={false}
                    ref={webcamRef}
                    screenshotFormat="image/jpeg"
                    width={500}
                    height={400}
                    videoConstraints={{
                        width: 500,
                        height: 400,
                        facingMode: "user"
                    }}
                    />  
                    <div className="guide"></div>
                </div>
                <button onClick={capture} className="button"><span>Take Photo </span></button>
            </>
            }
            
          </React.Fragment>
      );
    }
    
    export default Selfie;

Leave a Comment