Encount Encount - 1 year ago 261
React JSX Question

React cannot read property of undefined

Moving some code from react.createclass to extending Component i have run into a problem. Whilst mapping a component i have a function being passed through as a property so it could be accessed from that component. It worked find the 'previous way' but now it is throwing this error:
Uncaught TypeError: Cannot read property 'removeComment' of undefined

Initially I thought it just needed binding but with the following code I still get the error: (NB: it fails in the Comment component only - the similar code in CommentForm works as intended)

all(value, index) {
return <Comment author={value.author} key={index} removeComment={this.removeComment.bind(this)} >{value.comment}</Comment>
}
render() {
return(
<div>
{this.state.items.map(this.all)}
<CommentForm getNewComment = {this.getNewComment.bind(this)} />
</div>
);
}


I have also tried binding it within the constructor method

Thanks

Answer Source
all(value, index) {
    return <Comment author={value.author} key={index} removeComment={this.removeComment.bind(this)} >{value.comment}</Comment>
  }
    render() {
      return(
        <div>
          {this.state.items.map(this.all.bind(this))}
          <CommentForm getNewComment = {this.getNewComment.bind(this)} />
        </div>
      );
  }

When you run the map you need to bind the handler as map runs the handler in some other scope, and it will change the context of this.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download