Reputation: 1294
Im currently using React for a project where i work and i'm struggling binding state with the form i'm creating. So i have this :
getInitialState: function() {
return {
proofDivulgation: false,
proofDivulgationFedex: false,
proofDivulgationMail: false,
noticeRecidivism: false,
noticeRecidivismFedex: false,
noticeRecidivismEmail: false,
fedexAccount: '',
emergyContact: false
};
And i want to change those booleans whenever i'll modify a checkbox ( the value of those booleans should be the same as the checked value of a checkbox ). I got this React component too
<Toggle defaultChecked={this.state.proofDivulgation} onChange={this.handleCheckboxChange(this.state.proofDivulgation)} />
and this is the method attached to the onChange event :
handleCheckboxChange: function(booleanToSwitch){
console.log(booleanToSwitch);
this.replaceState({booleanToSwitch : true})
},
which give me this error : replaceState(...): Cannot update during an existing state transition (such as withinrender). Render methods should be a pure function of props and state.
Is there any work-around i could do ? I simply need a basic function that'll invert the boolean value of a state passed as a parameters
Upvotes: 1
Views: 1535
Reputation: 10163
You are calling that function immediately, not on change.
render
;onChange
parameter;onChange
;What your code does is set the return value of this.handleCheckboxChange(this.state.proofDivulgation)
as the callback for onChange
.
What you need is this:
handleCheckboxChange: function(booleanToSwitch) {
return function(event) {
console.log(booleanToSwitch);
this.replaceState({booleanToSwitch : true})
};
},
Also I'm pretty sure you'll need
this.state[booleanToSwitch] = true;
instead.
Upvotes: 1