Reputation: 550
I need to call a function in the parent after some async operation in the child. I get an error basically saying "this" is undefined.
Something like this:
class Parent extends React.Component {
......
openFile (path) {
...
if (someCondition) this.showMessage();
}
......
......
render() {
<Child openFile={this.openFile}/>
}
}
function Child ({ openFile }) {
......
const createNewFile = () => {
// using electron but doubt it matters
dialog.showOpenDialog(
// choose file location
).then(({path}) => {
openFile(path)
})
}
}
The error is "cannot read property 'showMessage' of undefined. Is there a correct way to pass the context in this situation?
Upvotes: 0
Views: 133
Reputation: 550
As pointed out in the comment, I needed to .bind(this)
in the parent class component.
Upvotes: 1