
I have created a React based SPFX project and will show you how to bind a dropdown control to code, in this scenario I am filling the data from choice column values from a SharePoint list.
You need to import Dropdown and IDropdownOption from office-ui-fabric-react in the .tsx file of your spfx web part which is also know a functional logic file. Use below snippet.
import {
Dropdown, IDropdownOption,
} from 'office-ui-fabric-react';
You can also bind dropdown control to retrieve data from multiple lists or can also multiple dropdown controls for creating a cascading logic. I have created a StatusDropdownOption array object using IDropdownOption interface.
Retrieve values form Column Field
Below is a small code logic which I have written to retrieve data from choice field. I am using the Issue Tracker list’s Status column and for binding the dropdown control
private StatusDropdownOption: IDropdownOption[] = [];
constructor(props:IDemoProps,state: IState)
{
super(props);
this.BindDropdown = this.BindDropdown.bind(this);
this.onStatusChanged = this.onStatusChanged.bind(this);
this.state ={
status:''
};
}
public async GetChoiceFieldOptions( listId: string, fieldInternalName: string ): Promise<{ key: string, text: string }[]> {
let fieldOptions: { key: string, text: string }[] = [];
try {
const results = await sp.web.lists.getById(listId)
.fields
.getByInternalNameOrTitle(fieldInternalName)
.select("Title", "InternalName", "Choices")
.get();
if (results && results.Choices.length > 0) {
for (const option of results.Choices) {
fieldOptions.push({
key: option,
text: option
});
}
}
} catch (error) {
return Promise.reject(error);
}
return fieldOptions;
}
private async BindDropdown() {
this.StatusDropdownOption = await this.GetChoiceFieldOptions( this.props.listId, "Status");
}
public async componentDidMount(){
await this.BindDropdown();
}
I have used a function BindDropdown because if I need to add more dropdown controls, I can use the same function. I also have used constructor of the class to the function/event bindings.
Binding the Dropdown control
Below is the syntax for binding the dropdown control:
<Dropdown
id='ddlStatus'
label={'Status'}
options={this.StatusDropdownOption}
placeholder={'Select Status'}
onChange={this.onStatusChanged} />
No Comments