Set disable/enabled value for text field based on a toggle value in React

1.1k Views Asked by At

I am creating a panel from Office Fabric:

  <div className={ styles.column }>
    <DefaultButton 
      onClick={this._showJobCreatePanel.bind(this)} text="Open Panel" 
    />
    <Panel
      isOpen={this.state.shouldShowJobCreatePanel}
      type={PanelType.smallFixedFar}
      onDismiss={this._hideJobCreatePanel.bind(this)}
      headerText="Create new Delivery Job"
      closeButtonAriaLabel="Cancel"
      onRenderFooterContent={this._onRenderFooterContent.bind(this)}
    >
      <ChoiceGroup
        options={trucksGroupOptions}
        required={true}
        label="Trucks"
        onChange={this._onChangeTruckChoice.bind(this)}
        style={divStyle} 
      ></ChoiceGroup>
      <Toggle
        defaultChecked={false}
        label="Out of Service"
        onText="Yes"
        offText="No"
        onChanged={newValue => {this._jobToCreate.OutOfService = newValue; this.setState({shouldDisableFields: newValue});}}
      ></Toggle>
      <TextField 
        disabled={this.state.shouldDisableFields} 
        required={!this.state.shouldDisableFields} 
        placeholder="Enter Customer" 
        label="Customer" 
        onChanged = {newValue => {this._jobToCreate.Title = newValue;}}
      ></TextField>
      <div style = {divStyle}></div>
    </Panel>
  </div>      

I want to disable the text field if the toggle is set to true. The code I have works, I toggle to true and the text fields are disabled.

The issue I'm having is when I call setState it is redrawing the panel and I'm losing the users' input for the ChoiceGroup.

I thought I could change the values of my IChoiceGroupOption[] group:

  <Toggle
    defaultChecked={false}
    label="Out of Service"
    onText="Yes"
    offText="No"
    onChanged={newValue => {
      for (let truckInOptions of trucksGroupOptions) {
        if (truckInOptions.key === this._jobToCreate.Truck) {
          truckInOptions.checked = newValue;
        }
      }
      console.log("truksGroupOptions: ", trucksGroupOptions);
      this._jobToCreate.OutOfService = newValue; 
      this.setState({shouldDisableFields: newValue});
    }}
  ></Toggle>

Checked is changing to true but the ChoiceGroup is still clearing out the choice.

How can I enable/disable the text fields based on the toggle value?

0

There are 0 best solutions below