I'm trying to create a function which would stop camera transmition and add this function to my exisitng code. This is the component that I am trying to change into a function:
class WebcamCapture extends React.Component {
setRef = (webcam) => {
this.webcam = webcam;
}
stop = () => {
let stream = this.webcam.video.srcObject;
const tracks = stream.getTracks();
tracks.forEach(track => track.stop());
this.webcam.video.srcObject = null;
};
render() {
return (
<div>
<Webcam
audio={false}
ref={this.setRef}
/>
<br />
<button
onClick={this.stop}
>Stop</button>
</div>
);
}
}
Below is how I tried to incorporate the stop function from the WebcamCapture component, but I get the following error: Cannot read properties of undefined (reading 'srcObject').
const Camera = () => {
const webcamRef = React.useRef(null);
const [imgSrc, setImgSrc] = React.useState(null);
const stop = React.useCallback(() => { //This is how I tried using stop function
let stream = webcamRef.video.srcObject;
const tracks = stream.getTracks();
tracks.forEach(track => track.stop());
webcamRef.video.srcObject = null;
},[webcamRef, setImgSrc]);
const capture = React.useCallback(() => {
const imageSrc = webcamRef.current.getScreenshot();
setImgSrc(imageSrc);
stop() //I would like to call stop() here
}, [webcamRef, setImgSrc]);
return (
<>
<Webcam
audio={false}
ref={webcamRef}
screenshotFormat="image/jpeg"
/>
<button onClick={capture} >Capture photo</button>
{imgSrc && (
<img
src={imgSrc}
/>
)}
</>
)
}
export default Camera
How could I get the stop function from the WebcamCapture component? Any help would be appreciated!
First, there is no need to add Ref in dependency array.
Second, if you are using ref and using "current" for getScreenshot function then you should use current for video object as well.
const Camera = () => {
const webcamRef = React.useRef(null);
const [imgSrc, setImgSrc] = React.useState(null);
const stop = React.useCallback(() => {
let stream = webcamRef.current.video.srcObject;
const tracks = stream.getTracks();
tracks.forEach(track => track.stop());
webcamRef.current.video.srcObject = null;
},[setImgSrc]);
const capture = React.useCallback(() => {
const imageSrc = webcamRef.current.getScreenshot();
setImgSrc(imageSrc);
stop()
}, [webcamRef, setImgSrc]);
return (
<>
<Webcam
audio={false}
ref={webcamRef}
screenshotFormat="image/jpeg"
/>
<button onClick={capture} >Capture photo</button>
{imgSrc && (
<img
src={imgSrc}
/>
)}
</>
)
}
export default Camera