Office-UI-Fabric-react uncheck checbox
-
02-01-2021 - |
Domanda
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
Soluzione
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:
Make sure to add a state variable to your state definition. Example:
export interface IExampleState { isChecked: boolean; }
Initialize your state in your constructor to a default value
constructor(props: IExampleProps) { super(props); (this); this.state = { isChecked: false }; }
Bind the checked attribute of your checkbox to your state. For example:
<Checkbox
checked={this.state.isChecked}
label="Standard checkbox"
onChange={ this._onControlledCheckboxChange }
/>Create an onClick event handler for your button that will change the state.
private _buttonClicked(): void { this.setState({ isChecked: true }); }
Bind the _buttonClicked event handler in your constructor:
constructor(props: IExampleProps) { super(props); this._buttonClicked = this._buttonClicked.bind(this); this.state = { isChecked: false };
Attach the _buttonClicked event handler to your button's onClick event:
<DefaultButton
text="Button"
onClick={this._buttonClicked}
/>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?!