2

I'm using Office UI Fabric React dropdown in my spfx webpart. I have added static options in that dropdown as below, but I want to bind options dynamically which i'm getting from REST api.

<Dropdown
placeholder="Select"
label="Select Location (Lookup)"
id="ddlLocation"
options={[                       
    { key: 'A', text: 'Option a' },
    { key: 'B', text: 'Option b' },
    { key: 'D', text: 'Option d' },
    { key: 'E', text: 'Option e' }                      
]}

If I'm not wrong then we have to pass function in options parameter which will return data in that format. If any one know then please help.

Thank you.

1 Answer 1

4

Init a property, which stores your options inside component's class:

private options: any[] = [];

Then load options dynamically (it depends on your application's logic), for example using async http function, you can init options in componentDidMount:

public async componentDidMount(): Promise<void> {
    this.categories = await SpService.getAllCategories();

    this.options = [];
    this.categories.forEach(c => {
      this.options.push({
        key: c.id,
        text: c.title
      });
    });
  } 

In render:

<Dropdown
    label='Category:'
    options={this.options}
    errorMessage={this.categoryError}
    onChanged={this.onCategoryChanged}
/>

To make it work you should also trigger component re-render after async data is received. If you don't do it, then move options property to a state and call this.setState from componentDidMount method. That way you can initialize your options with some dynamic async data.

2
  • 1
    It works ! Thanks a lots Sergei for your quick help :-) Commented Jan 27, 2019 at 14:32
  • It worked to me as well.
    – Swetha
    Commented Nov 26, 2020 at 14:06

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.