How to set default value in select using js

I have two dropdownin my example with a reset ( select bank select state) state . Only the first drop-down list has data. When I change the first dropdown value, I get the status data and show it in the drop down list. if I choose YES BANK, show me select state. Now, if I select any example state Delhi. then do something. But now, if I change the bank again instead of YES BANKexample Axis bankstate dropdown show DelhiWhy? Does it show reset and show select state?

like reset the second drop-down menu (when the first drop-down menu changes). have my code

https://codesandbox.io/s/7wlwx2volq

The second drop-down menu always shows select statewith new data bankwhen the user changesbank name

 onChangeDropdown = e => {
    console.log(e.target.value);
    this.props.callbackFn(e.target.value);
  };

Explain, please

+4
source share
1 answer

One possible solution: instead of using the selected property in the parameters, use a controlled component using the value property of the select field. Whenever any changes occur to the bank list, reset the status of the state selected for applying. Also set the parameter value=''with the default parameter.

Like this:

<select value={this.props.value} onChange={this.onChangeDropdown}>
    <option value='' disabled>
        {this.props.defaultOption}
    </option>

    {makeDropDown()}
</select>;

Pass the value from the parent component, for example:

<DropDown
    value={this.state.bankName}
    data={this.state.bankData}
    defaultOption="select Bank"
    callbackFn={this.callStateService}
/>
<DropDown
    value={this.state.stateName}
    data={this.state.stateData}
    defaultOption="select State"
    callbackFn={this.callDistrictService}
/>

Define the onChange function to change the state selection field:

callDistrictService = value => {
    this.setState({ stateName: value });
}

Working sandbox.

+4
source

Source: https://habr.com/ru/post/1694276/


All Articles