Im new in React and typescript.
The thing im trying to do: I have a class component, which renders a functional camera component. When the user save an image (from the camera component), i want to use that base64 string in the parent component. Hope it makes sense.
My Class component (parent)
class Form extends React.Component<any, any>{
constructor(props: any) {
super(props);
this.state = { ... }
...
public render() {
<div className="cameraSection">
{this.state.displayCamera &&
<WebcamCapture />
}
</div>
}
My camera component:
import * as React from 'react';
import { useEffect, useRef, useState, useCallback } from 'react';
import Webcam from 'react-webcam'
const WebcamCapture = (props: any) => {
const webcamRef = useRef(null);
let [imgSrc, setImgSrc] = useState<string | null>(null);
const capture = useCallback(() => {
const base64 = (webcamRef as any).current.getScreenshot();
setImgSrc(base64);
}, [webcamRef, setImgSrc])
return (
<>
<div className="row">
<Webcam
audio={false}
ref={webcamRef}
screenshotFormat="image/jpeg"
videoConstraints={videoConstraints}
/>
<button onClick={capture}>Take picture</button>
</div>
{imgSrc && (<>
<div className="row">
<img src={imgSrc} />
<div className="col-md-3">
<button onClick={() => {setImgSrc(null)}}>delete</button>
</div>
</div>
</>
)}
</>
);
I'ts the 'imgSrc' i want to access from the class component.
-Thanks.
You would use a callback that you pass to your child. When a screenshot is taken you call it in the child passing the data to it:
and