I am calling an API and output of that API I am putting on the dropdown list.
These are the country code in my drop down list. I want to put default message in drop down like.
"Please select the country code" once user click then he can select countrycode. here by default EF is selected. in place of EF I want to put message.
Below output I am putting on the list.
componentDidMount() {
axios.get(`http://localhost:8080/country_code`).then((res) => {
const countryData = res.data;
this.setState({ countryData });
alert(countryData);
});
}
dropdown code
<select
name="countriesValue"
value={this.state.countriesValue}
onChange={this.selectCountryCode}
>
{this.state.countryData.map((countryData) => (
<option key={countryData} value={countryData}>
{countryData}
</option>
))}
</select>
method:-
selectCountryCode(e) {
e.preventDefault();
this.setState({ countriesValue: e.target.value });
}
state variable
this.state = {
countryCode: '',
countryData: [],
countriesValue: '',
};
what mistake I am doing in my select
>Solution :
To add a default value to the <select> element, you can add a disabled and hidden option like the following:
<select
name="countriesValue"
value={this.state.countriesValue}
onChange={this.selectCountryCode}
>
<option value="" selected disabled hidden>Please select the country code</option>
{this.state.countryData.map((countryData) => (
<option key={countryData} value={countryData}>
{countryData}
</option>
))}
</select>
