0

I am new to spfx webpart. I have following clarification.

Is it possible to populate choice column values of a library to drop down control dynamically.

Note: I don't want to display dropdown as webpart property.

Dropdown is a control inside webpart.

Thanks.

1 Answer 1

2

You can use the below code:

const dropdownStyles: Partial<IDropdownStyles> = {
  dropdown: { width: 300 }
};
const options: IDropdownOption[] = [  
  { key: 'apple', text: 'Apple' },
  { key: 'banana', text: 'Banana' },
  { key: 'orange', text: 'Orange'},
  { key: 'grape', text: 'Grape' },
  { key: 'broccoli', text: 'Broccoli' },
  { key: 'carrot', text: 'Carrot' },
  { key: 'lettuce', text: 'Lettuce' }
];
const stackTokens: IStackTokens = { childrenGap: 20 };

Add below stack tag inside render return function

<Stack tokens={stackTokens}>
      <Dropdown placeholder="Select an option" label="Basic uncontrolled example" options={options} styles={dropdownStyles} />
    </Stack>

Above code with static JSON Data:

Now dynamically add the dropdown list using the SharePoint list data:

var items: IDropdownOption[]=[];

export interface IReactGetItemsState{ 
  items: IDropdownOption[];
} 

Then add then below constructor inside the class method to initialise the state

public constructor(props: ISpfxReactReadProps, state: IReactGetItemsState){ 
    super(props); 
    this.state = { 
      items: []
    }; 
  } 

Add the below ‘componentDidMount()’ method just below the constructor method. This method retrieves SharePoint list items using pnp sp js and sets it in the state using ‘setState’

public async componentDidMount(): Promise<void>
  {
    // get all the items from a sharepoint list
    var reacthandler=this;
    sp.web.lists.getByTitle("Projects").items.select('Title').get().then(function(data){
      for(var k in data){
        items.push({key:data[k].Title, text:data[k].Title});
      }
      reacthandler.setState({items});
      console.log(items);
      return items;
    });
  }

Example: Load dropdown list using the SharePoint list item in SPFx

For details implementation refer to the below article:

SPFX Load SharePoint list items in a dropdown using PNP SP JS

1
  • @Ropaesh: If the above answered helped you or answered your question - could you please mark as answered - so that it will help the upcoming visitors. Thanks for your understanding. :-)
    – SP 2022
    Apr 11, 2020 at 6:15

Your Answer

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

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