How to populate select dropdown elements with data from API – ReactJS

All we need is an easy explanation of the problem, so here it is.

I’m fairly new to React. I’m fetching data from an API, and I can see the data when I check console log. However I can’t figure out how I can use map() to create a new array which the option elements can then use to display the currency codes.

Currently it populates the dropdown, but the option elements are all empty and results show up as NaN.

Below is a sample of my code where I am fetching the data.

state = {
    currencies: [],
    base: "USD", //default value
    amount: "",
    convertTo: "EUR",
    result: ""
  };

componentDidMount() {
    fetch("https://api.exchangeratesapi.io/latest")
      .then(response => {
        return response.json();
      })
      .then(data => {
        let currenciesFromApi = Object.keys(data.rates);
        console.log(currenciesFromApi);
        this.setState({
          currencies: currenciesFromApi
        });
      })
      .catch(error => {
        console.log(error);
      });
  }

Expected Results: Dropdown to be populated with currency codes from API (eg GBP, EUR, USD) and value to display rates and not NaN.

Actual Results: Dropdowns are empty and selecting any of these also return Nan.

How to solve :

I know you bored from this bug, So we are here to help you! Take a deep breath and look at the explanation of your problem. We have many solutions to this problem, But we recommend you to use the first method because it is tested & true method that will 100% work for you.

Method 1

I checked the source code and it seem the array of currencies contains just string values. So when you map through them to render the options, just use the variable directly as a string.

{this.state.currencies.map(currency => (
  <option key={currency} value={currency}>
    {currency}
  </option>
))}

See: https://codesandbox.io/s/hu8cb

Note: Use and implement method 1 because this method fully tested our system.
Thank you 🙂

All methods was sourced from stackoverflow.com or stackexchange.com, is licensed under cc by-sa 2.5, cc by-sa 3.0 and cc by-sa 4.0

Leave a Reply