Reputation: 1052
I am trying to update the state of the parent bypassing the handler function to the child but I am getting an error:
class Parent(){
contractor(props){
super(props);
this.state = {
answer: ""
}
};
hanadleAnswer = _answer => {
this.setState({ answer: _answer });
}
render () {
return (
<Switch>
<Route path="questions" component={<Child handler={_answer => this.handleAnswer(_answer)}/>}
</Switch>
)
}
}
In the child, I wanted to update the state of the answer according to the sent answer of option
function Child({ handler }){
...
<Button onClick={handler({option_1})}></Button>
<Button onClick={handler({option_2})}></Button>
...
}
I realized that the handler is fired even without clicking on the button, with an error message:
Unhandled Rejection (Error): Maximum update depth exceeded. This can happen when a component repeatedly calls setState inside componentWillUpdate or componentDidUpdate. React limits the number of nested updates to prevent infinite loops.
If this method doesn't work, how can I update the state of the parent according to the value coming from child bu buttons?
Upvotes: 1
Views: 47
Reputation: 9769
use like this-
function Child({ handler }){
...
<Button onClick={()=>handler({option_1})}></Button>
<Button onClick={()=>handler({option_2})}></Button>
...
}
Reference for better understanding Handling Events . Quoting from that page:
Passing Arguments to Event Handlers
Inside a loop, it is common to want to pass an extra parameter to an event handler. For example, if id is the row ID, either of the following would work:
<button onClick={(e) => this.deleteRow(id, e)}>Delete Row</button> <button onClick={this.deleteRow.bind(this, id)}>Delete Row</button>
Upvotes: 3