I'm so sorry for how badly worded that title is but I'm just learning React and I got something working in what feels like a bit of a hacky way, and I'm trying to figure it out properly.
Here's the code that I initially couldn't get to work (the removeItem part was throwing an error as this.removeItem was undefined).
render() {
return (
<div className="App">
<AddItem addItem={this.addItem.bind(this)} />
<ul>
{this.state.listItems.map(function(item,index){
return (
<ListItem id={index} key={index} title={item} removeItem={this.removeItem.bind(this)} />
);
})}
</ul>
</div>
);
}
I realised that it was something to do with scope, in that "this" inside map() was not referring to the same "this" that addItem is. The solution I came up with was just to define "this" in a separate variable for use inside the map().
render() {
var theApp = this;
return (
<div className="App">
<AddItem addItem={this.addItem.bind(this)} />
<ul>
{this.state.listItems.map(function(item,index){
return (
<ListItem id={index} key={index} title={item} removeItem={theApp.removeItem.bind(theApp)} />
);
})}
</ul>
</div>
);
}
My query is - I don't feel like I've seen this kind of approach in other peoples' code or tutorials or such, but I can't quite get my head round what's going on and what would be a better way of handling this. Any thoughts, or even pointers on what to Google much appreciated!