Ad

Event Callback For React Components In An Array Only Loads For Last Component Rendered

- 1 answer

In short I have an array of ReactJS components. I have a callback after the load of an image so I can render it on a canvas.

The relevant code where the callback is found below found below.

 componentDidMount:function(){  
    
    this.props.video.src = this.props.video_src;
    this.props.thumbnail.src = this.props.thumbnail_src;

    var context = ReactDOM.findDOMNode(this).getContext('2d');
    console.log(context);
    
    this.setState({context: context});

    this.props.thumbnail.onload = function(){     
      if(this.state.context != null){
	console.log("prop is done loading");
	this.state.context.drawImage(this.props.thumbnail,0,0,320,200);
      }
    }.bind(this);                
  }

I am fetching the DOM node like such because my render function simply returns

  render:function(){    
    return(
     	<canvas width="320" height="200"></canvas>
    )    
  }  

I have an array of a number of these elements in a parent component. All these child components are mounting but only the last element in the array seems to load the image via the callback.

Any ideas? I feel I am going wrong at my onload event.

Ad

Answer

There are a couple things wrong here that might be the issue

1) don't modify props, they are immutable

this.props.video.src = this.props.video_src;
this.props.thumbnail.src = this.props.thumbnail_src;

2) You should use a ref to target the canvas like so

componentDidMount:function(){ 
   ...
   var context = ReactDOM.findDOMNode(this.refs.canvas);
   ...
}

render:function(){    
    return(
        <canvas ref="canvas" width="320" height="200"></canvas>
    )    
}  

Is the code above for the parent component or the child?

Ad
source: stackoverflow.com
Ad