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

It could be bit silly doing a basic operation. But thought of sharing this could help someone.

What I am going do here?

I want to display SharePoint list items in a dropdown in SPFX webpart.

  • As Microsoft recommends to use OUIFR(Office UI Fabric React) for design consistency I am going to use it rather than an normal html dropdown.
  • Also, for retrieving SharePoint list items I will use PNPSPJS

Step 1: Create SPFX React webpart

Step 2: Add Office UI fabric dropdown list to webpart with sample data:

For more details refer Microsoft site here

Add below import statements in ‘SpfxReactRead.tsx’

Add these 3 constant variables, one is to support the dropdown style and another one is to supply array values to dropdown

Add below stack tag inside render return function

Then let’s see how the added dropdown looks like. Go with ‘Gulp serve’. I got the below error messages and the build failed

To fix them ctrl + click on the links will take to through the code line. Just comment them and re run ‘Gulp serve’ will work

Now local workbench loads, and I have added my webpart looks great with the Office UI fabric dropdown control added with the dummy data.

Step 3: Read SP list items using PNPSPJS

To read SP list items we are going to use pnp js, so install the libraries with the below command

Note: Normally we won’t use all these so no need to install everything, but some are interrelated, so I usually install all.

Add the below code just above the class method

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

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’

Step 4: Load SP list items to populate in drop down

As we are ready with the list items available in state, we can map it to the dropdown by changing the updating “options={this.state.items}”. It looks like this.

Cool. We are ready hit “Gulp serve” but local workbench will not the load any data as it needs a SharePoint site. So, go to SharePoint site workbench in my case it is “https://cogsharepoint.sharepoint.com/sites/Accounts/_layouts/15/workbench.aspx

And add the webpart into the page. Fantastic!!! we could see the SharePoint list items loaded into the dropdown list.

Thanks for reading my blog. Sharing is caring #sharingiscaring.