Reputation: 11030
When I run the onEditNoteClick function, I am returned an error that says
Cannot read property 'onEditNoteClick' of undefined
I'm not sure why I'm getting this issue. To make it simpler, I set the onEditNoteClick parameter to 1 but it still doesn't work.
constructor(props) {
super(props);
this.onEditNoteClick = this.onEditNoteClick.bind(this);
}
......
onEditNoteClick(id){
console.log("came to this function");
}
renderNotes(note) {
return (
<tr key={note.id}>
<td> {note.name}</td>
<td> {note.description} </td>
<td className="edit" onClick={this.onEditNoteClick.bind(this,1)}><i className="fa fa-fw fa-pencil fa-lg"></i> </td>
</tr>
);
}
.....
render(){
{this.props.notes.map(this.renderNotes)}
I think I need to add a bind method with the notes map, something like this:
{this.props.notes.map(this.renderNotes).bind(this)}
But I'm not sure what the correct syntax is.
Upvotes: 1
Views: 1516
Reputation: 816552
I think I need to add a bind method with the notes map, something like this:
{this.props.notes.map(this.renderNotes).bind(this)}
That would be incorrect. .bind
can only be called on a function, but .map
returns an array, not a function. What you have to is set the this
value of the this.renderNotes
method. The easiest way to achieve this would be to pass this
as second argument to .map
(see the documentation):
{this.props.notes.map(this.renderNotes, this)}
Alternatively, bind this.renderNotes
in the constructor
just like you do with the other method:
this.renderNotes = this.renderNotes.bind(this);
and then you can omit the second argument:
{this.props.notes.map(this.renderNotes)}
See also: How to access the correct `this` context inside a callback?
Upvotes: 2