I try to implement a class table in react. A table has multiple rows, each having a button. As a start, I try to pass a function handleEvent.
Now, I always end up with: TypeError: Cannot read property '_doDeleteItem' of undefined
There is some kind of binding error, but i cannot figure it out.
Cheers
class Table extends Component {
constructor(props,context) {
super(props,context);
this.state = { k : 3 };
this._handleEvent = this._handleEvent.bind(this);
}
_handleEvent (e) {
console.log('delete')
}
render() {
var rows = [];
var lastCategory = null;
this.props.results.slice(-this.state.k).forEach(function(r) {
rows.push( <Rows result = {r} deleteItem = {this._handleEvent} />);
});
return(
<Panel>
<ListGroup fill>
{rows}
</ListGroup>
</Panel>
);
}
}
export default Table;
class Rows extends Component{
render() {
return(
<ListGroupItem>
<b>Text:</b><Button onClick = {this.props.deleteItem} type="False"><b>True</b></Button><br/>
</ListGroupItem>
);
}
}
this
is not the component instance inside the forEach
. Either use an arrow function, bind the anonymous function, or pass this
as the second argument to forEach
:
this.props.results.slice(-this.state.k).forEach(function(r) {
rows.push( <Rows result = {r} deleteItem = {this._handleEvent} />);
}.bind(this));
or
this.props.results.slice(-this.state.k).forEach(function(r) {
rows.push( <Rows result = {r} deleteItem = {this._handleEvent} />);
}, this);