React Select - How to show / iterate through data from api call in option instead of hardcoding options?

可紊 提交于 2019-12-21 17:05:32

问题


I am using react-select and I don't want to hard code the options which should be displayed, but options is data I am fetching from an api. I can't really find anything and what I was trying to do doesn't work as nothing gets displayed. Anyone knows? Thanks!!!

api.js:

export function availableCities() {
   return axios.get('/cities').then(function (response) {
      return response.data;
   })
}

Component:

import Select from 'react-select';
import {availableCities} from '../utils/api.js';

class App extends React.Component {
    constructor(props) {
    super(props);
    this.state = {
        selectedOption: '',
        clearable: true,
        cities: [],
     } 
   }
   componentDidMount() {
    availableCities()
        .then(res => {
            this.setState({
                cities: res.Cities.name
            })
            console.log("hello", this.state.cities)
        })
   }

   handleChange(selectedOption) {
    this.setState({selectedOption});
   }
 render(){
    let options = this.state.cities.map(function (city) {
            return city.name;
    })
 return (
      <div>
           <Select
                name="form-field-name"
                value={this.state.value}
                onChange={this.handleChange}
                clearable={this.state.clearable}
                searchable={this.state.searchable}
                options={options}                  
            />
      </div>
  )
 }
}

Data( this.state.cities is an array of objects and looks like:

{code: "LTS", name: "Altus", countryCode: "US", countryName: "United States", regionName: "North America", …}

...

回答1:


The issue here comes from the objects in your array. react-select needs an array of objects with following keys in order to understand it: value and label.

So, in render, you could replace

let options = this.state.cities.map(function (city) {
  return city.name;
})

by, for example,

let options = this.state.cities.map(function (city) {
  return { value: city.countryCode, label: city.name };
})

or, like pritesh pointed out, simply tell react-select what keys to use like

render () {
  return (
    <div>
      <Select
        name="form-field-name"
        value={this.state.value}
        onChange={this.handleChange}
        clearable={this.state.clearable}
        searchable={this.state.searchable}
        labelKey='name'
        valueKey='countryCode'
        options={this.state.cities}                  
      />
    </div>
  )
}

Hope this helps you out!




回答2:


In your return component you can simply pass the cities that is fetched from api as

import Select from 'react-select';
import {availableCities} from '../utils/api.js';

let isLoadingExternally = false;

class App extends React.Component {

    constructor(props) {
    super(props);
    this.state = {
        selectedOption: '',
        clearable: true,
        cities: [],
    } 
}
componentDidMount() {
    isLoadingExternally = true;
    availableCities()
        .then(res => {
            this.setState({
                cities: res.Cities.name
            }, () => {
                isLoadingExternally = false;
            })
            console.log("hello", this.state.cities)
        })
}

handleChange(selectedOption) {
    this.setState({selectedOption});
}
render(){
return (
    <div>
        <Select
                name="form-field-name"
                value={this.state.value}
                onChange={this.handleChange}
                clearable={this.state.clearable}
                searchable={this.state.searchable}
                labelKey={'name'}
                valueKey={'code'}
                isLoading={isLoadingExternally}
                options={this.state.cities}                  
            />
    </div>
)
}
}

There are lots of configurable options available in the docs.




回答3:


Try this :

renderList() {
 return (this.state.responseData.map(data =>({label:data.Name,value:data.value})))
}

and Call :

 <Select
    options={this.renderList()}
/>


来源:https://stackoverflow.com/questions/47672117/react-select-how-to-show-iterate-through-data-from-api-call-in-option-instea

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!