1

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

1 Answer 1

1

You are calling that function immediately, not on change.

  1. React runs render;
  2. It finds an onChange parameter;
  3. If it's a function reference then nothing happens;
  4. If it's a function call then the function is called when the code runs and the result is passed as the callback to onChange;
  5. When you click on the checkbox that function reference (callback) is called;

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.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.