Reputation: 3149
I have in my code a simple form where I can alert input data. So In my first class, I define a function. Then I pass that function to another class.
class IndecisionApp extends React.Component {
constructor(props){
super(props)
this.handleAddOption = this.handleAddOption.bind(this)
this.state = {
options: ['test1,test2,test3']
}
}
handleAddOption(option) {
console.log(option)
}
render(){
return (
<div>
<AddOption
handleAddOption={this.handleAddOption}
/>
</div>
)
}
}
class AddOption extends React.Component {
handleAddOption(e) {
e.preventDefault()
const option = e.target.elements.option.value.trim()
if(option) {
this.props.handleAddOption(option)
}
}
render(){
return(
<div>
<form onSubmit={this.handleAddOption}>
<input type="text" name="option"/>
<button>Add Option</button>
</form>
</div>
)
}
}
ReactDOM.render(<IndecisionApp />, document.getElementById('app'))
This line of code this.props.handleAddOption(option)
gives me the error.
Uncaught TypeError: Cannot read property 'props' of undefined
at handleAddOption (app.js:64)
at HTMLUnknownElement.callCallback (react-dom.development.js:1527)
at Object.invokeGuardedCallbackDev (react-dom.development.js:1566)
at Object.invokeGuardedCallback (react-dom.development.js:1423)
at Object.invokeGuardedCallbackAndCatchFirstError (react-dom.development.js:1437)
at executeDispatch (react-dom.development.js:1660)
at Object.executeDispatchesInOrder (react-dom.development.js:1682)
at executeDispatchesAndRelease (react-dom.development.js:2197)
at executeDispatchesAndReleaseTopLevel (react-dom.development.js:2208)
at Array.forEach (<anonymous>)
at forEachAccumulated (react-dom.development.js:2174)
at Object.processEventQueue (react-dom.development.js:2367)
at runEventQueueInBatch (react-dom.development.js:2379)
at Object.handleTopLevel [as _handleTopLevel] (react-dom.development.js:2389)
at handleTopLevelImpl (react-dom.development.js:2028)
at batchedUpdates (react-dom.development.js:14309)
at performFiberBatchedUpdates (react-dom.development.js:1874)
at stackBatchedUpdates (react-dom.development.js:1865)
at batchedUpdates (react-dom.development.js:1879)
at Object.batchedUpdatesWithControlledComponents [as batchedUpdates] (react-dom.development.js:1892)
at dispatchEvent (react-dom.development.js:2102)
I am binding the handleAddOption inside the constructor, so I don't know why I am getting that error. What did I miss?
Thanks, Theo.
Upvotes: 0
Views: 44
Reputation: 3274
You need to bind handleAddOption of class AddOption to this:
class AddOption extends React.Component {
constructor(props) {
super(props);
this.handleAddOption = this.handleAddOption.bind(this)
}
Upvotes: 0
Reputation: 15146
You need to add the constructor()
inside the <AddOption />
, too.
class AddOption extends React.Component {
constructor(props){
super(props)
this.handleAddOption = this.handleAddOption.bind(this)
...
}
...
Upvotes: 2