Bind SharePoint List Items to SPFx fluent ui react dropdown example

If you have a requirement to bind SharePoint list items in a dropdown list in SharePoint Framework client-side webpart, keep reading. In this SPFx tutorial, I have explained in detail, how to bind SharePoint List Items to SPFx fluent ui react dropdown with an example.

Recently I got a requirement, where I had a SharePoint list, and I need to bind the SharePoint list item in the Spfx webpart dropdown. Even if we will add an item to SharePoint that also reflects in the dropdown in the client side webpart.

If you are new to SPFx development, check out how to do spfx development setup and also check out how to develop an spfx client-side web part in SharePoint Online.

Bind SharePoint List Items to SPFx fluent ui react dropdown

Here we will see how to bind SharePoint list items to fluent ui react dropdown in a SharePoint Framework client-side web part.

Before we will create a project, we need a SharePoint list with items. So here I have just created a product list with a SharePoint list item, like below with below column names:

  • Title (Single line of text)
  • ProductName (Single line of text).
Bind SharePoint List Items to SPFx fluent ui react dropdown
SharePoint List Items

By the end of the tutorial, you will be able to create a client-side webpart using the SharePoint framework and bind SharePoint list items to a fluent ui react dropdown. It will look like below:

Bind SharePoint List Items to SPFx fluent ui react dropdown example
Bind SharePoint List Items to SPFx fluent ui react dropdown example

Now, let us create our SPFx client-side webpart.

Step 1: Open the node.js command prompt, and then create a project folder, and navigate to the Project folder.

mkdir ProductDropdown
cd ProductDropdown

Step 2: Run the below code to create the project by the yeoman SharePoint generator.

yo @microsoft/sharepoint

Then yeoman SharePoint generator will ask you a list of questions to create an spfx project.

  • ? What is your solution name? product-dropdown (provide the solution name for the project )
  • ? Which type of client-side component to create? WebPart(here you can see four choices I.e. Webpart, Extension, Library, Adaptive Card Extension, and select Extension)
  • ? What is your Web part name? ProductDropdown (here provide the web part name)
  • ? Which template would you like to use? React(It will provide 3 options :Minimal, React, No Framework)
SPFx fluent ui react dropdown
SPFx fluent ui react dropdown example

It will take some time, to download and install all the dependencies required for the solution. Once the SPFx solution is created successfully, you can see a success message below.

SPFx fluent ui react dropdown example
SPFx fluent ui react dropdown example

Step 3: Then install some of the required libraries which we will use in our solution.

Here we will use the fluent ui react dropdown control, so we need to install the required libraries.

To install fluent UI libraries, write the below command to install:

npm install @fluentui/react

We need to get SharePoint list items using pnp js, so we are required to install the pnp js. To install the javascript library for SharePoint, write the below command to install:

npm install sp-pnp-js

Step 4: Once the prerequisites are installed successfully, let us open the solution using visual studio code. So to open the project in VS code. run the below command.

Code .

You can see the project structure on the left side of the code editor (VS code editor).

SharePoint framework fluent ui react dropdown
SharePoint framework fluent ui react dropdown

Step 5: First we will create an interface for the SharePoint list item, i.e. ISPListProductItem. For this inside the component folder ‘src\webparts\productDropdown\components’ create a file with the name ‘IProducts.ts’. Then write the below code:

export interface ISPListProductItem{
    Id:any;
    Title:string;
    ProductName:string;
  }

Step 6: Then we will create a class by using the above interface, and on that, we will create a public member and then assign the type. For this, create a file in the component ‘src\webparts\productDropdown\components’ i.e. ‘ClassProduct.ts’. Then write the below code:

import { ISPListProductItem } from "./IProducts";

export class  ClassProduct{
    public ProductName:string;
    public Id:any
    constructor(item: ISPListProductItem) {
      this.ProductName = item.ProductName;
      this.Id=item.Id

  }
}

Step 7: Now open the ProductDropdown.tsx file, located in the ‘ src\webparts\productDropdown\components\ProductDropdown.tsx’. First, we will import the below files:

import pnp from 'sp-pnp-js'
import { ClassProduct } from './ClassProduct';
// import { ISPListProductItem } from './IProducts';
import {Dropdown, IDropdownOption} from '@fluentui/react';

Step 8: Then in the IProductDropdownState interface, write the below code:

export interface IProductDropdownState {
  selectedProduct?: IDropdownOption;
  items: IDropdownOption[];
}

Step 9: After that, above the render method create a constructor like the below:

export default class ProductDropdown extends React.Component<IProductDropdownProps, IProductDropdownState> {
  constructor(props: IProductDropdownProps) {
    super(props);
    this.state = {
      selectedProduct: undefined,
      items: []
    };
  }
......
}

Step 10: Then in the same file, change the code of the render method with the below code. Inside this method, we created a function ‘_getListProductData()’ in which we will retrieve the SharePoint list items, and then we will bind them to the spfx webpart dropdown.

public render(): React.ReactElement<IProductDropdownProps> {
    return (
      <section className={`${styles.productDropdown}`}>
        <Dropdown
          label="Select a product"
          options={this.state.items}
          selectedKey={this.state.selectedProduct?.key}
          onChange={this.onDropdownChange}
        />
      </section>
    );
  }

  public componentDidMount(){
    this._getListProductData();
  }

  private _getListProductData() : void {
    pnp.sp.web.lists.getByTitle(`Product`).items.get().then((response: any) => {
      let productCollection = response.map((item: any) => new ClassProduct(item));
      let dropdownOptions = productCollection.map((product: ClassProduct) => {
        return {
          key: product.Id,
          text: product.ProductName
        };
      });
      this.setState({ items: dropdownOptions });
    });
  }

  private onDropdownChange = (event: React.FormEvent<HTMLDivElement>, item: IDropdownOption): void => {
    this.setState({ selectedProduct: item });
  }
}

Here is the full code of the .tsx file:

import * as React from 'react';
import styles from './ProductDropdown.module.scss';
import { IProductDropdownProps } from './IProductDropdownProps';
import pnp from 'sp-pnp-js'
import { ClassProduct } from './ClassProduct';
// import { ISPListProductItem } from './IProducts';
import {Dropdown, IDropdownOption} from '@fluentui/react';

export interface IProductDropdownState {
  selectedProduct?: IDropdownOption;
  items: IDropdownOption[];
}

export default class ProductDropdown extends React.Component<IProductDropdownProps, IProductDropdownState> {
  constructor(props: IProductDropdownProps) {
    super(props);
    this.state = {
      selectedProduct: undefined,
      items: []
    };
  }

  public render(): React.ReactElement<IProductDropdownProps> {
    return (
      <section className={`${styles.productDropdown}`}>
        <Dropdown
          label="Select a product"
          options={this.state.items}
          selectedKey={this.state.selectedProduct?.key}
          onChange={this.onDropdownChange}
        />
      </section>
    );
  }

  public componentDidMount(){
    this._getListProductData();
  }

  private _getListProductData() : void {
    pnp.sp.web.lists.getByTitle(`Product`).items.get().then((response: any) => {
      let productCollection = response.map((item: any) => new ClassProduct(item));
      let dropdownOptions = productCollection.map((product: ClassProduct) => {
        return {
          key: product.Id,
          text: product.ProductName
        };
      });
      this.setState({ items: dropdownOptions });
    });
  }

  private onDropdownChange = (event: React.FormEvent<HTMLDivElement>, item: IDropdownOption): void => {
    this.setState({ selectedProduct: item });
  }
}

Step 10: Paste the below code in the .ts file located in the ‘src\webparts\productDropdown\ProductDropdownWebPart.ts

import * as React from 'react';
import * as ReactDom from 'react-dom';
import { Version } from '@microsoft/sp-core-library';
import {
  IPropertyPaneConfiguration,
  PropertyPaneTextField
} from '@microsoft/sp-property-pane';
import { BaseClientSideWebPart } from '@microsoft/sp-webpart-base';

import * as strings from 'ProductDropdownWebPartStrings';
import ProductDropdown from './components/ProductDropdown';
import { IProductDropdownProps } from './components/IProductDropdownProps';

export interface IProductDropdownWebPartProps {
  description: string;
}

export default class ProductDropdownWebPart extends BaseClientSideWebPart<IProductDropdownWebPartProps> {

  public async render(): Promise <void> {
    const element: React.ReactElement<IProductDropdownProps> = React.createElement(
      ProductDropdown,
    );

    ReactDom.render(element, this.domElement);
  }

  protected onDispose(): void {
    ReactDom.unmountComponentAtNode(this.domElement);
  }

  protected get dataVersion(): Version {
    return Version.parse('1.0');
  }

  protected getPropertyPaneConfiguration(): IPropertyPaneConfiguration {
    return {
      pages: [
        {
          header: {
            description: strings.PropertyPaneDescription
          },
          groups: [
            {
              groupName: strings.BasicGroupName,
              groupFields: [
                PropertyPaneTextField('description', {
                  label: strings.DescriptionFieldLabel
                })
              ]
            }
          ]
        }
      ]
    };
  }
}

Step 11: Now we will configure the local server to run and test our project, so for this navigate to ‘config\serve.json‘ and provide the SharePoint site URL on the internal page.

Bind sharepoint online list items in SPFx
Bind sharepoint online list items in SPFx

Now, to compile and run the code, run the below command.

gulp serve

Once you will run the above command, it will open the local workbench where we can add our webpart and test it.

In the browser, click on the + icon, then select the web part -> then click on the dropdown you can see the list of product names, which you have added to the SharePoint list item. Also if you will add an item or product name to the list then it will reflect in the dropdown.

How to bind SharePoint list items in the Spfx webpart dropdown
How to bind SharePoint list items in the Spfx webpart dropdown

This is how to bind SharePoint List Items to SPFx fluent ui react dropdown and we saw a complete example of that.

Download SPFx fluent ui react dropdown example Solution

Download the complete solution of SPFx fluent ui react dropdown example. And then run the below command, it will add the node_modules to the solution and then it will run without any errors.

npm i

Conclusion

In this spfx tutorial, we saw how to bind Bind sharePoint List Items to SPFx fluent ui react dropdown.