I am working on ReactJS with multiple ponents in parent-child mode. In the following example, update function is passed on to the Note ponent (child) from Board ponent (parent). When I execute the code, I get Uncaught TypeError: Cannot read property 'update' of undefined
error and I have a bind(this) in the constructor.
import React, { Component } from 'react';
import Note from './note';
export default class Board extends Component {
constructor(props) {
super(props);
this.state = {
notes: [
'Call Bill',
'Email list',
'Fix evernote tags'
]
};
this.update = this.update.bind(this);
}
update(newText,i){
alert('update triggered');
var arr = this.state.notes;
arr[i]=newText;
this.setState({notes:arr});
};
eachNote(note,i){
return(
<Note key={i} index={i} onNoteChange={this.update}>{note}</Note>
);
};
render() {
return (
<div className="board">
{ this.state.notes.map(this.eachNote) }
</div>
);
}
}
I would appreciate any help in resolving this issue. And once the binding in place, I should be able to call this parent method in the child ponent right ?
I am working on ReactJS with multiple ponents in parent-child mode. In the following example, update function is passed on to the Note ponent (child) from Board ponent (parent). When I execute the code, I get Uncaught TypeError: Cannot read property 'update' of undefined
error and I have a bind(this) in the constructor.
import React, { Component } from 'react';
import Note from './note';
export default class Board extends Component {
constructor(props) {
super(props);
this.state = {
notes: [
'Call Bill',
'Email list',
'Fix evernote tags'
]
};
this.update = this.update.bind(this);
}
update(newText,i){
alert('update triggered');
var arr = this.state.notes;
arr[i]=newText;
this.setState({notes:arr});
};
eachNote(note,i){
return(
<Note key={i} index={i} onNoteChange={this.update}>{note}</Note>
);
};
render() {
return (
<div className="board">
{ this.state.notes.map(this.eachNote) }
</div>
);
}
}
I would appreciate any help in resolving this issue. And once the binding in place, I should be able to call this parent method in the child ponent right ?
Share Improve this question edited Jan 13, 2016 at 12:54 Felix Kling 817k181 gold badges1.1k silver badges1.2k bronze badges asked Jan 13, 2016 at 9:00 cucucoolcucucool 3,8879 gold badges52 silver badges63 bronze badges 1- Possible duplicate of Uncaught TypeError: Cannot read property 'Checked' of undefined - ReactJS – Felix Kling Commented Jan 13, 2016 at 12:54
2 Answers
Reset to default 5this
in eachNote
does not refer to Board
, it refers to global scope(in browser it is window
) or if you use strict mode
(I think you use it) it will be undefined
, you need set it
{ this.state.notes.map(this.eachNote, this) }
__^^^^___
In addition to @Alexander answer, you can bind eachNote
to this
in constructor too and it should work:
this.eachNote = this.eachNote.bind(this);