9

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", …}

...
2
  • 1
    You are assigning, cities: res.Cities.name. Is this is correct? or cities: res.Cities ?
    – Madhavan.V
    Commented Dec 6, 2017 at 10:42
  • yes,sorry it should be cities: res.Cities Commented Dec 6, 2017 at 12:57

3 Answers 3

16

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!

4
  • 3
    You can explicitly set the value and label with valueKey and labelKey options so no need to map
    – pritesh
    Commented Dec 6, 2017 at 10:46
  • @pritesh thank you for pointing that out, I edited my post accordingly
    – 3Dos
    Commented Dec 6, 2017 at 10:52
  • Thank you very much!!! It works now :) Just one more question: my when I set state with selectedOption, it always shown undefined. When I assign it to the value, I keep getting errors.. Commented Dec 6, 2017 at 13:00
  • try onChange={this.handleChange.bind(this)} as this is not bound to the function in an eventListener context. Another solution would be to declare handleChange as an arrow function like handleChange = (selectedOption) => {this.setState({ currentOption: selectedOption });} don't forget the state key in setState
    – 3Dos
    Commented Dec 6, 2017 at 14:02
3

Try this :

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

and Call :

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

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.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.