3

How Can I uncheck a checkbox dynamically from the code?

I need to uncheck some checkboxes at the same time from the code when I press a button.

I'm using:

SharePoint Framework - Typescript - Office UI Fabric - React

2

Fabio,

I'm assuming that you're using Office UI Fabric Checkbox and DefaultButton for this answer -- let me know if you aren't.

To solve this issue use the following steps:

  1. Make sure to add a state variable to your state definition. Example:

    export interface IExampleState {
      isChecked: boolean;
    }
    
  2. Initialize your state in your constructor to a default value

    constructor(props: IExampleProps) {
        super(props);
    (this);
        this.state = {
          isChecked: false
        };
      }
    
  3. Bind the checked attribute of your checkbox to your state. For example:

    <Checkbox
    checked={this.state.isChecked}
    label="Standard checkbox"
    onChange={ this._onControlledCheckboxChange }
    />

  4. Create an onClick event handler for your button that will change the state.

    private _buttonClicked(): void {
      this.setState({ isChecked: true });
    }
    
  5. Bind the _buttonClicked event handler in your constructor:

    constructor(props: IExampleProps) { super(props); this._buttonClicked = this._buttonClicked.bind(this); this.state = { isChecked: false };

  6. Attach the _buttonClicked event handler to your button's onClick event:

    <DefaultButton
    text="Button"
    onClick={this._buttonClicked}
    />

  7. This should be it. Note that I force the checkbox to true when the button is clicked, but you could toggle is as well:

    private _buttonClicked(): void {
      this.setState({ **isChecked: this.state.isChecked!});**
    }
    

I hope this helps?!

| improve this answer | |

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.