title: React - Get the ref present in child component in the parent component
body: <p>I'm not trying to do anything hacky using refs. I just need the ref to the element because the element is a canvas, and to draw on a canvas you need its ref.</p>
  
  <pre><code>class Parent extends Component {
    clickDraw = () =&gt; {
      // when button clicked, get the canvas context and draw on it.
      // how?
    }
  
    render() {
      return (
        &lt;div&gt;
          &lt;button onClick={this.clickDraw}&gt; Draw &lt;/button&gt;
          &lt;Child /&gt;
        &lt;/div&gt;
      );
    }
  }
  
  
  class Child extends Component {
    componentDidMount() {
      const ctx = this.canvas.getContext('2d');
      // draw something on the canvas once it's mounted
      ctx.fillStyle = "#FF0000";
      ctx.fillRect(0,0,150,75);
    }
  
    render() {
      return (
        &lt;canvas width={300}
                height={500}
                ref={canvasRef =&gt; this.canvas = canvasRef}&gt;
        &lt;/canvas&gt;
      );
    }
  }
  </code></pre>
  
  <p>=====  </p>
  
  <p>Something I tried (which technically works but feels strange) is define the <code>&lt;canvas&gt;</code> in the parent, so in its ref function, <code>this</code> refers to the parent component. Then I pass the <code>&lt;canvas&gt;</code> and <code>this.canvas</code> to the child as two separate props. I return the <code>&lt;canvas&gt;</code> (named <code>this.props.canvasJSX</code>) in the child's render function, and I use <code>this.canvas</code> (named <code>this.props.canvasRef</code>) to get its context to draw on it. See below:</p>
  
  <pre><code>class Parent extends Component {
    clickDraw = () =&gt; {
      // now I have access to the canvas context and can draw
      const ctx = this.canvas.getContext('2d');
      ctx.fillStyle = "#00FF00";
      ctx.fillRect(0,0,275,250);
    }
  
    render() {
      const canvas = (
        &lt;canvas width={300}
                height={500}
                ref={canvasRef =&gt; this.canvas = canvasRef}&gt;
        &lt;/canvas&gt;
      );
      return (
        &lt;div&gt;
          &lt;button onClick={this.clickDraw}&gt; Draw &lt;/button&gt;
          &lt;Child canvasJSX={canvas}
                 canvasRef={this.canvas} /&gt;
        &lt;/div&gt;
      );
    }
  }
  
  
  class Child extends Component {
    componentDidMount() {
      const ctx = this.props.canvasRef.getContext('2d');
      // draw something on the canvas once it's mounted
      ctx.fillStyle = "#FF0000";
      ctx.fillRect(0,0,150,75);
    }
  
    render() {
      return this.props.canvas;
    }
  }
  </code></pre>
  
  <p>Is there a more standard way of achieving this?</p>