Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

putting message in dropdownlist in react

I am calling an API and output of that API I am putting on the dropdown list.

enter image description here

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.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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>
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading