Souvik Ghosh
Souvik Ghosh

Reputation: 4606

Dynamically bind Dropdown items Material-UI

This question may be duplicate or trivial but i can't seem to make it work.

I am using Matrial-UI in my React.js app to implement dropdown like this.

<Select native value={this.state.contractType} onChange={this.handleChange} input={<OutlinedInput id="contractType"/> }>
    {this.fetchContractTypes}
</Select>

fetchContractTypes gets the dropdown values from a database.

fetchContractTypes = async () => {
    const dropDownValues = await ProjectAPI.getDropDownValues();
    const contractValues = dropDownValues.filter(value => value.type === 'contract');
    const data = [];
    contractValues[0].value.map(val => {
        data.push(<option key={val.id} value={val.id}>{ val.name }</option>)
    });
    console.log(data);
    return data;
}

I can see the dropdown values are being fetched in the browser console window but the items are not getting binded. Any idea how I can make this work?

Upvotes: 2

Views: 4608

Answers (1)

J&#248;rgen
J&#248;rgen

Reputation: 360

Fetch data before render and put it in component state

I suggest you fetch the data in a useEffect hook (if you are using hooks) or componentDidMount() of you are using class based components. Then set the fetched value as sate and reference your state in the render method.

componentDidMount(){
    this.fetchContractTypes()
}

Set state in your fetchContractTypes()

fetchContractTypes = async () => {
    const dropDownValues = await ProjectAPI.getDropDownValues();
    const contractValues = dropDownValues.filter(value => value.type === 'contract');
    const data = [];
    contractValues[0].value.map(val => {
        data.push(<option key={val.id} value={val.id}>{ val.name }</option>)
    });
    this.setState({contractTypes: data});
}

Reference state in render

<Select native value={this.state.contractType} onChange={this.handleChange} input={<OutlinedInput id="contractType"/> }>
    {this.state.contractTypes}
</Select>

Upvotes: 1

Related Questions