ReactJS - how to pass component reference to another component as prop?

Viewed 5647

I have two sibling components WebcamStream and CaptureArea, I want to pass reference to WebcamStream as prop of CaptureArea, but when I do this, it always null. How to fix this ?

class AppContent extends React.Component {
    constructor(props) {
        super(props);
        this.videoTag = React.createRef();
    }

    render() {
        return (
            <div id="content">
                <WebcamStream ref={this.videoTag}
                              width="300" height="300" 
                              title="Real-time video stream from webcam" 
                              id="video" />
                <CaptureArea x="20" y="20" width="120" 
                             height="120" color="white" 
                             videoTag={this.videoTag.current}/>
            </div>
        );
    }
}

Why I need this: CaptureArea generates temporary canvas on current video tag to get imageData from it. I use imageData to parse QR Code.

1 Answers

ref is a prop used by React internally much like the key prop, so you can name it something else and treat it like any other prop in the WebcamStream component.

innerRef is a common name for a custom ref that you attach to any of the elements in the component.

Example

function WebcamStream(props) {
  return <div ref={props.innerRef}> WebcamStream </div>;
}

class CaptureArea extends React.Component {
  componentDidMount() {
    console.log(this.props.videoTag.current);
  }
  render() {
    return <div> CaptureArea </div>;
  }
}

class AppContent extends React.Component {
  videoTag = React.createRef();

  render() {
    return (
      <div id="content">
        <WebcamStream
          innerRef={this.videoTag}
          width="300"
          height="300"
          title="Real-time video stream from webcam"
          id="video"
        />
        <CaptureArea
          x="20"
          y="20"
          width="120"
          height="120"
          color="white"
          videoTag={this.videoTag}
        />
      </div>
    );
  }
}

ReactDOM.render(<AppContent />, document.getElementById("root"));
<script src="https://unpkg.com/react@16.6.1/umd/react.production.min.js"></script>
<script src="https://unpkg.com/react-dom@16.6.1/umd/react-dom.production.min.js"></script>

<div id="root"></div>

Related