1
votes

I am having issues with

const imageSrc = webcamRef.current.getScreenshot();

Error: Object is possibly 'null';

and src={imgSrc}

<img src={imgSrc} />

Error: Type 'null' is not assignable to type 'string | undefined'.ts(2322) index.d.ts(2053, 9): The expected type comes from property 'src' which is declared here on type 'DetailedHTMLProps<ImgHTMLAttributes, HTMLImageElement>'

Full code below:

import React, { createRef, useRef, useState } from "react";
import Webcam from "react-webcam";

const WebcamCapture = () => {
    const webcamRef = useRef(null);
    const [imgSrc, setImgSrc] = useState(null);

    const capture = React.useCallback(() => {
        const imageSrc = webcamRef.current.getScreenshot();
        setImgSrc(imageSrc);
    }, [webcamRef, setImgSrc]);

    return (
        <>
            <Webcam
                audio={false}
                ref={webcamRef}
                screenshotFormat="image/jpeg"
            />
            <button onClick={capture}>Capture photo</button>
            {imgSrc && (
                <img
                    src={imgSrc}
                />
            )}
        </>
    );
};

export default WebcamCapture;
2

2 Answers

1
votes

Here's the solution:

 const webcamRef = useRef<Webcam>(null);
 const [imgSrc, setImgSrc] = useState<string | null>(null);
1
votes

Even after adding the above lines it didn't worked for me.

Checking current null or not worked for me.

if (webcamRef.current) {
  const imageSrc = webcamRef.current.getScreenshot();
  setImgSrc(imageSrc);
}