Passing data from Child functional component to parent - React/Typescript

2k views Asked by At

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.

2

There are 2 answers

0
trixn On

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:

class Form extends React.Component<any, any>{
  state = { /* ... */ };

  handleCapture = base64img => {
    // use the base64 string
    console.log(base64img);
  };

  public render() {
    <div className="cameraSection">
        {this.state.displayCamera && (
          <WebcamCapture onCapture={this.handleCapture} />
        )}
    </div>
}

and

const WebcamCapture = ({onCapture}: any) => {
  const webcamRef = useRef(null);
  let [imgSrc, setImgSrc] = useState<string | null>(null);

  const capture = useCallback(() => {
    const base64 = (webcamRef as any).current.getScreenshot();
    
    setImgSrc(base64);

    // call the callback
    onCapture(base64);
  }, [setImgSrc, onCapture])

  // ...
}
0
Punit Makwana On

In Parent Component

// dont forgot to bind this
updateBase64(data){
    this.setState(base64: data});
}

render(){
 return(
   ...
   <WebcamCapture updateBase64={this.updateBase64}/>);
   ...
}1

In Child Component

props.updateBase64(base64)