1

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.

3

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.

  • 1
    It works ! Thanks a lots Sergei for your quick help :-) – SP Developer Jan 27 at 14:32

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

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