Reputation: 77
Working with React app and try to show options within the dropdown like feature, I am using <Select>
tag of react-select
.Everything is fine with api fetching and data are available. However, It shows no options in the dropdown menu.
import React, { Component } from 'react';
import Select from 'react-select';
import url from '../services/urlService';
class TechCompanies extends Component {
state = {
values: []
}
componentDidMount() {
fetch(url + 'api/roles/roles')
.then(res => res.json())
.then(res => this.setState({
values: res.Data
}))
.catch(error => console.log(error))
}
render() {
return (
<div>
<Select>
{this.state.values.map((role) => {
return <option key={role.RoleId} value={role.RoleId}
>{role.RoleName}</option>
})}
</Select>
</div>
)
}
}
export default TechCompanies;
Upvotes: 0
Views: 5149
Reputation: 20755
react-select
need options
attribute.
You can create option
array using your this.state.values
,
let option = []
if (this.state.values.length > 0) {
this.state.values.forEach(role => {
let roleDate = {}
roleDate.value = role.RoleId
roleDate.label = role.RoleName
option.push(roleDate)
})
}
Usage
<Select options={options} />
Note:: Also make sure you get response from your API call, to get guaranteed response you must use async
-await
to fetch data.
Upvotes: 1
Reputation: 1797
this worked for me. you just pass your array as prop options
to Select
component. you can also pass onChange
handler as prop as well as currently selected value.
render() {
return (
<div>
<Select
options={this.state.values}>
</Select>
</div>
)
}
you can find more about it on their npm page https://www.npmjs.com/package/react-select
Upvotes: 2