Search code examples
javascriptnode.jsreactjsjavascript-objectsfetch-api

React - Fill select dropdown with data from API


I want to fill my select>options with datas fetched from api. Everything works fine, I can see my datas on console or another div, but in option tags they seem like Object object. How can I fix it ? Here are my codes:

    state = {
        loading: true,
        city: null,
    }
    async componentDidMount(){
        const url = ...;
        const response = await fetch(url, {
            headers: {
                ...
            }
        })
        const data = await response.json();
        this.setState({city: data.results[0], loading: false})
    }

...

<select>
  <option>Select city</option>
  <option>
    {this.state.loading || !this.state.city ? (<p>Loading...</p>) : 
    (<p>{ this.state.city.name }</p>)}
  </option>
</select>

p.s: I should display not only 0-th datas properties, but all of datas' properties.


Solution

  • <option>
        {this.state.loading || !this.state.city ? (<p>Loading...</p>) : 
        (<p>{ this.state.city.name }</p>)}
      </option>
    

    The above code will not work as

    or any other tag cannot reside inside option tag the p tag get outside the option tag and not visible enter image description here