title: How to use react to draw rectangles over objects in an image?
body: <p>I'm using react and HTML5 canvas to draw rectangles over faces on an image, but react life-cycle is limiting me from doing this.</p>
  
  <p>As I should use refs to reference to the canvas and this have to be done in componentDidMount() and I could not get props or states inside this function.</p>
  
  <p>Here is the code:</p>
  
  <pre><code>import React, { Component } from 'react'
  import { render } from 'react-dom'
  import {Row} from 'react-bootstrap';    
  import '../App.css';
  
  class TagImg extends Component {
    constructor(props){
      super(props);
      this.state={
        rects:[[110, 30, 70, 70], [40, 30, 70, 70]],
        ctx : ''
      };
      this.tagPerson = this.tagPerson.bind(this);
    }
  
    tagPerson(e){
      var x = e.offsetX,
          y = e.offsetY;
  
      for(var i=0;i&lt;this.props.rects.length;i++) { // check whether:
          if(x &gt; this.props.rects[i][0]            // mouse x between x and x + width
          &amp;&amp; x &lt; this.props.rects[i][0] + this.props.rects[i][2]
          &amp;&amp; y &gt; this.props.rects[i][1]            // mouse y between y and y + height
          &amp;&amp; y &lt; this.props.rects[i][1] + this.props.rects[i][3]) {
              alert('Rectangle ' + i + ' clicked');
          }
      }
    }
  
    componentDidMount() {
      console.log("componentDidMount");
      const ctx = this.refs.canvas.getContext('2d');
      var myImage = new Image();
  
      myImage.onload = function() {
        var width = myImage.naturalWidth; // this will be 300
        var height = myImage.naturalHeight; // this will be 400
        ctx.drawImage(myImage, 0, 0, 300, 200);
  
        ctx.beginPath();
        ctx.strokeStyle="white";
        // for(var i=0;i&lt;this.state.rects.length;i++) {
        //   // ctx.rect(this.state.rects[i][0], // fill at (x, y) with (width, height)
        //   //          this.state.rects[i][1],
        //   //          this.state.rects[i][2],
        //   //          this.state.rects[i][3]);
        //   console.log("helloo");
        // }
        console.log(this.state.rects);
  
        ctx.stroke();
      }
      myImage.src = this.props.path;
    }
    render() {
      return (
        &lt;div&gt;
        &lt;form id="afterUpload" action="" method="post" encType="multipart/form-data"&gt;
          &lt;Row id="image_preview" className="row"&gt;
            &lt;canvas ref="canvas" onClick={this.tagPerson}/&gt;
          &lt;/Row&gt;
        &lt;/form&gt;
        &lt;/div&gt;
      );
    }
  }
  
  export default TagImg;
  </code></pre>
  
  <p>After searching I figured out that I could use componentWillRecieveProps() but did not understand how to use it in my case.</p>