I have two dropdown
in my example with reset state (select bank
select state
).only first dropdown have data .When I changed first dropdown value then i fetch state data and show in dropdown . if i select YES BANK
it show me select state
.Now if I select any state example Delhi
.then do something.But Now If I change again bank instead of yes bank
example Axis bank
state dropdown show Delhi
why ? it show be reset and show select state
?
how to reset second dropdown (when first dropdown is change).here is my code
https://codesandbox.io/s/7wlwx2volq
Second dropdown always show select state
with new data of bank
,when user change bank name
onChangeDropdown = e => {
console.log(e.target.value);
this.props.callbackFn(e.target.value);
};
please explain
In HTML, the 'selected' attribute in the option tag is used to set the default value in the select menu. The same approach can also be used with React to set a default value if we are not using React Select Component.
The default value of the select element can be set by using the 'selected' attribute on the required option. This is a boolean attribute. The option that is having the 'selected' attribute will be displayed by default on the dropdown list.
To set a default value for an input element in React:Pass the default value as a parameter to the useState hook for controlled fields. Set the defaultValue prop on uncontrolled input fields.
Setting value for the select React provides us with a shared API between <input type="text"> , <textarea> and <select> where we can use value or defaultValue (depending if the input is controlled or not) to set the field's value.
One possible solution is: Instead of using the selected property on options, use controlled component means use the value property of select field. Whenever any change happen to bank list, reset the value of state select filed value. Also define the value=''
with default option.
Like this:
<select value={this.props.value} onChange={this.onChangeDropdown}>
<option value='' disabled>
{this.props.defaultOption}
</option>
{makeDropDown()}
</select>;
Pass value from parent component, like this:
<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 onChange function for state select field change:
callDistrictService = value => {
this.setState({ stateName: value });
}
Working Sandbox.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With