Live training: next batches coming soon. Join the waitlist:Waitlists open:Developer Training →Developer →Copilot Studio Training →Copilot Studio →

Bind SharePoint List Items to an SPFx Fluent UI React Dropdown (PnPjs, REST, Graph)

Many guides still fill an SPFx dropdown with sp-pnp-js and test it with gulp serve. It works on old projects, but sp-pnp-js is deprecated on npm and gulp left the SPFx toolchain in version 1.22.

The better answer: read the items with PnPjs v4 (or SPHttpClient or Microsoft Graph), map each one to { key: Id, text: Title }, and pass that array to the Fluent UI Dropdown as its options.

In this tutorial, we’ll bind SharePoint list items to an SPFx Fluent UI React Dropdown in a real web part. You’ll see all three data methods side by side, a dropdown filled from a choice column, a cascading order dropdown, a property pane dropdown and the Heft commands to run and package it.

Tested withVersion
SharePoint Framework1.23.2 (Heft toolchain)
Node.js22 LTS
React / Fluent UI17.0.1 / @fluentui/react 8
PnPjs@pnp/sp 4.22.0

The sample lists we’ll use

Everything in this post reads two lists on my SPGuides site. SPGDemo Products holds four products (Laptop Stand, Monitor Arm, USB-C Dock, Wireless Mouse), and its ID and Title become the first dropdown’s options. If you only need to show items in a grid, start with displaying SharePoint list items in an SPFx web part instead.

SPGDemo Orders has 210 orders. These are the columns the web part uses:

ColumnTypeUsed for
TitleSingle line of textOrder number, e.g. SO-1002
CustomerNameSingle line of textOrder dropdown text + details
ProductLookup to SPGDemo ProductsFilter orders by the selected product
OrderStatusChoice: New, Processing, Shipped, DeliveredSecond dropdown (choice field)
Quantity, OrderTotal (Currency), OrderDate, PaidNumber, Currency, Date, Yes/NoDetails card

One row is tricky on purpose: SO-1001 (Northwind Traders) has no product, quantity or date. It never shows up in a product filter, and the details card has to cope with blank values.

SPGDemo Products list on the SPGuides site with the four product items used as dropdown options

sp-pnp-js is retired: the PnPjs v4 equivalent

If you landed here searching for import pnp from 'sp-pnp-js', here’s the short version. sp-pnp-js was the first PnP JavaScript library. Its npm page now says it’s deprecated and points you to the new @pnp/* packages, and its last release (3.0.10) predates SPFx 1.18 by years.

This is what the old code looked like:

// Old (sp-pnp-js, retired) - don't copy this into a new project
import pnp from 'sp-pnp-js';

pnp.sp.web.lists.getByTitle('Products').items.select('ID', 'Title').get()
  .then((items: any[]) => { /* set state */ });

And this is the PnPjs v4 version of the same call:

// New (PnPjs v4)
import { spfi, SPFx } from '@pnp/sp';
import '@pnp/sp/webs';
import '@pnp/sp/lists';
import '@pnp/sp/items';

const sp = spfi().using(SPFx(this.context));   // once, in onInit
const items = await sp.web.lists.getByTitle('SPGDemo Products').items.select('Id', 'Title')();

How does this work?

There’s no default pnp object and no global sp.setup() anymore. You create your own sp instance with spfi(), and SPFx(this.context) hands it the web part’s authentication and site URL.

The side-effect imports (@pnp/sp/lists, @pnp/sp/items) add only the features you use, which keeps the bundle small. Errors like “sp-pnp-js has no exported member sp” or “getbytitle is not a function” usually mean an old sample is mixing the two libraries.

The same jump happened to the build tools. If your project still runs gulp, follow migrating an SPFx project from gulp to Heft first.

Build the web part step by step

Here’s the full build, the way I did it in VS Code. If your machine isn’t ready for SPFx yet, set up Node.js 22 and the tools with the SPFx development environment guide for Heft.

1. Create the project. Run these commands in a terminal (the VS Code integrated terminal works fine). The yo answers create a React web part for SharePoint Online:

yo @microsoft/sharepoint --solution-name spg-list-dropdown --component-type webpart --component-name ListDropdown --framework react --environment spo
cd spg-list-dropdown
npm install
npm install @pnp/sp@4.22.0 @pnp/queryable@4.22.0 @microsoft/sp-http@1.23.2 --save-exact

PnPjs is the only extra library. @microsoft/sp-http brings SPHttpClient and MSGraphClientV3, and Fluent UI 8 already comes with the React template. If npm stops with EPERM or ENOENT errors, see fixing npm install errors in SPFx.

2. Add the files. I keep data access out of the React component. Each method lives in its own service class, and all three follow one contract, so the component never knows where the data came from:

src/webparts/listDropdown/
  models/IOrderModels.ts          <- shapes + the IOrderService contract
  services/PnPOrderService.ts     <- Method 1: PnPjs v4
  services/RestOrderService.ts    <- Method 2: SPHttpClient REST
  services/GraphOrderService.ts   <- Method 3: Microsoft Graph
  components/IListDropdownProps.ts
  components/ListDropdown.tsx     <- the Fluent UI Dropdowns
  components/ListDropdown.module.scss
  ListDropdownWebPart.ts          <- picks the service, property pane
VS Code Explorer showing the models, services and components folders of the SPFx list dropdown web part

3. Create the models file at src/webparts/listDropdown/models/IOrderModels.ts:

// Shapes the React component works with - the same for every data method.
export interface IProduct {
  id: number;
  title: string;
}

export interface IOrder {
  id: number;
  title: string;          // order number, e.g. SO-1002
  customerName: string;
  quantity?: number;
  orderTotal?: number;
  orderDate?: string;      // ISO date string
  orderStatus: string;
  paid: boolean;
}

// Every data method (PnPjs, SPHttpClient, Graph) implements this contract.
export interface IOrderService {
  getProducts(): Promise<IProduct[]>;
  getStatusChoices(): Promise<string[]>;
  getOrders(productId: number, status?: string): Promise<IOrder[]>;
}

export const PRODUCTS_LIST: string = 'SPGDemo Products';
export const ORDERS_LIST: string = 'SPGDemo Orders';

IProduct is all a dropdown option needs: an ID for the key and a title for the text. IOrderService is the contract every method below implements.

Method 1: Bind the dropdown with PnPjs v4 (Recommended)

Use PnPjs for almost every web part. The code is short, typed and readable, and it handles the request digest and URL building for you.

Here’s src/webparts/listDropdown/services/PnPOrderService.ts:

import { spfi, SPFI, SPFx } from '@pnp/sp';
import '@pnp/sp/webs';
import '@pnp/sp/lists';
import '@pnp/sp/items';
import '@pnp/sp/fields';
import { WebPartContext } from '@microsoft/sp-webpart-base';
import { IOrder, IOrderService, IProduct, ORDERS_LIST, PRODUCTS_LIST } from '../models/IOrderModels';

// Method 1: PnPjs v4 (recommended)
export class PnPOrderService implements IOrderService {
  private _sp: SPFI;

  constructor(context: WebPartContext) {
    this._sp = spfi().using(SPFx(context));
  }

  public async getProducts(): Promise<IProduct[]> {
    const items: { Id: number; Title: string }[] = await this._sp.web.lists
      .getByTitle(PRODUCTS_LIST)
      .items.select('Id', 'Title')
      .orderBy('Title')();
    return items.map(i => ({ id: i.Id, title: i.Title }));
  }

  public async getStatusChoices(): Promise<string[]> {
    const field: { Choices: string[] } = await this._sp.web.lists
      .getByTitle(ORDERS_LIST)
      .fields.getByInternalNameOrTitle('OrderStatus')
      .select('Choices')();
    return field.Choices;
  }

  public async getOrders(productId: number, status?: string): Promise<IOrder[]> {
    let filter: string = `ProductId eq ${productId}`;
    if (status) {
      filter += ` and OrderStatus eq '${status}'`;
    }
    const items: any[] = await this._sp.web.lists // eslint-disable-line @typescript-eslint/no-explicit-any
      .getByTitle(ORDERS_LIST)
      .items.select('Id', 'Title', 'CustomerName', 'Quantity', 'OrderTotal', 'OrderDate', 'OrderStatus', 'Paid')
      .filter(filter)
      .orderBy('Title')
      .top(500)();
    return items.map(i => ({
      id: i.Id,
      title: i.Title,
      customerName: i.CustomerName || '',
      quantity: i.Quantity ?? undefined,
      orderTotal: i.OrderTotal ?? undefined,
      orderDate: i.OrderDate ?? undefined,
      orderStatus: i.OrderStatus || '',
      paid: !!i.Paid
    }));
  }
}
PnPOrderService.ts open in VS Code with the PnPjs v4 getByTitle items select query

How does this work?

getProducts() asks SPGDemo Products for only two columns, sorted by title, and maps the four items to { id, title }. Selecting just the columns you need keeps the response small.

getStatusChoices() reads the Choices property of the OrderStatus field. That’s how you bind a dropdown to a choice column: the options come from the column definition, so a new choice shows up without a code change.

getOrders() filters on ProductId, the hidden ID column SharePoint creates for every lookup. I cover more filter patterns in filtering SharePoint list items in SPFx.

Render the Fluent UI Dropdown from the list items

Now the React side. The component loads the options once, keeps the selections in state and reloads the orders when the product or status changes. New to the control library? See Fluent UI in SharePoint Framework for the basics.

Here’s src/webparts/listDropdown/components/IListDropdownProps.ts:

import { IOrderService } from '../models/IOrderModels';

export interface IListDropdownProps {
  service: IOrderService;
  methodName: string;         // shown in the header so you can see which data method ran
  defaultProductId?: number;  // picked in the property pane
}

And the component, src/webparts/listDropdown/components/ListDropdown.tsx:

import * as React from 'react';
import { Dropdown, IDropdownOption, MessageBar, MessageBarType, Spinner, Stack, Text } from '@fluentui/react';
import styles from './ListDropdown.module.scss';
import { IListDropdownProps } from './IListDropdownProps';
import { IOrder } from '../models/IOrderModels';

const ALL: string = '__all';
const usd = new Intl.NumberFormat('en-US', { style: 'currency', currency: 'USD' });

const ListDropdown: React.FC<IListDropdownProps> = ({ service, methodName, defaultProductId }) => {
  const [productOptions, setProductOptions] = React.useState<IDropdownOption[]>([]);
  const [statusOptions, setStatusOptions] = React.useState<IDropdownOption[]>([]);
  const [orders, setOrders] = React.useState<IOrder[]>([]);
  const [productId, setProductId] = React.useState<number | undefined>(defaultProductId);
  const [status, setStatus] = React.useState<string>(ALL);
  const [orderId, setOrderId] = React.useState<number | undefined>();
  const [loading, setLoading] = React.useState<boolean>(true);
  const [error, setError] = React.useState<string>('');

  // 1. Load the product options and the OrderStatus choices once
  React.useEffect(() => {
    Promise.all([service.getProducts(), service.getStatusChoices()])
      .then(([products, choices]) => {
        setProductOptions(products.map(p => ({ key: p.id, text: p.title })));
        setStatusOptions([{ key: ALL, text: 'All statuses' }, ...choices.map(c => ({ key: c, text: c }))]);
        setLoading(false);
      })
      .catch((e: Error) => {
        setError(e.message);
        setLoading(false);
      });
  }, [service]);

  // Follow the default product when it changes in the property pane
  React.useEffect(() => setProductId(defaultProductId), [defaultProductId]);

  // 2. Reload the orders whenever the product or status changes
  React.useEffect(() => {
    setOrderId(undefined);
    if (productId === undefined) {
      setOrders([]);
      return;
    }
    service.getOrders(productId, status === ALL ? undefined : status)
      .then(setOrders)
      .catch((e: Error) => setError(e.message));
  }, [service, productId, status]);

  const orderOptions: IDropdownOption[] = orders.map(o => ({ key: o.id, text: `${o.title} - ${o.customerName}` }));
  const selected: IOrder | undefined = orders.find(o => o.id === orderId);

  if (loading) {
    return <Spinner label="Loading products..." />;
  }

  return (
    <section className={styles.listDropdown}>
      <Text variant="large" block>Product orders <span className={styles.method}>({methodName})</span></Text>
      {error && <MessageBar messageBarType={MessageBarType.error}>{error}</MessageBar>}
      <Stack horizontal wrap tokens={{ childrenGap: 16 }}>
        <Dropdown
          label="Product"
          placeholder="Select a product"
          options={productOptions}
          selectedKey={productId ?? null}
          onChange={(_, option) => setProductId(option ? Number(option.key) : undefined)}
          styles={{ root: { width: 220 } }}
        />
        <Dropdown
          label="Order status"
          options={statusOptions}
          selectedKey={status}
          onChange={(_, option) => setStatus(option ? String(option.key) : ALL)}
          styles={{ root: { width: 180 } }}
        />
        <Dropdown
          label={`Order (${orders.length})`}
          placeholder={productId === undefined ? 'Pick a product first' : 'Select an order'}
          options={orderOptions}
          selectedKey={orderId ?? null}
          disabled={orders.length === 0}
          onChange={(_, option) => setOrderId(option ? Number(option.key) : undefined)}
          styles={{ root: { width: 280 } }}
        />
      </Stack>
      {selected && (
        <dl className={styles.details}>
          <dt>Order</dt><dd>{selected.title}</dd>
          <dt>Customer</dt><dd>{selected.customerName || '-'}</dd>
          <dt>Quantity</dt><dd>{selected.quantity ?? '-'}</dd>
          <dt>Order total</dt><dd>{selected.orderTotal !== undefined ? usd.format(selected.orderTotal) : '-'}</dd>
          <dt>Order date</dt><dd>{selected.orderDate ? new Date(selected.orderDate).toLocaleDateString('en-US') : '-'}</dd>
          <dt>Status</dt><dd>{selected.orderStatus || '-'}</dd>
          <dt>Paid</dt><dd>{selected.paid ? 'Yes' : 'No'}</dd>
        </dl>
      )}
    </section>
  );
};

export default ListDropdown;

How does this work?

The key line is products.map(p => ({ key: p.id, text: p.title })). Fluent UI’s Dropdown wants an array of IDropdownOption objects, and the item ID makes a stable key even when two products share a name.

The details card formats the total with Intl.NumberFormat in USD and the date with toLocaleDateString('en-US'). For other patterns, see formatting dates in SPFx.

selectedKey makes the dropdowns controlled, so React state is the single source of truth. Passing null (not undefined) clears the selection and shows the placeholder again.

The Order dropdown is a cascading dropdown: its options depend on the Product and Order status values, and it stays disabled until there’s something to pick.

Some styling for the details card goes in ListDropdown.module.scss:

.listDropdown {
  color: var(--bodyText);

  .method {
    font-size: 14px;
    color: #605e5c;
  }

  .details {
    display: grid;
    grid-template-columns: 120px 1fr;
    gap: 6px 12px;
    margin: 20px 0 0;
    padding: 16px;
    max-width: 520px;
    border-left: 4px solid #0078d4;
    background: #f3f9fd;

    dt {
      font-weight: 600;
    }

    dd {
      margin: 0;
    }
  }
}

Wire up the web part and a property pane dropdown

The web part file creates the three services once in onInit and passes the selected one to the component. It also adds two property pane dropdowns, which covers the other meaning of “SharePoint dropdown web part”. For more pane controls, see SPFx property pane controls.

Here’s src/webparts/listDropdown/ListDropdownWebPart.ts:

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

import ListDropdown from './components/ListDropdown';
import { IListDropdownProps } from './components/IListDropdownProps';
import { IOrderService } from './models/IOrderModels';
import { PnPOrderService } from './services/PnPOrderService';
import { RestOrderService } from './services/RestOrderService';
import { GraphOrderService } from './services/GraphOrderService';

export interface IListDropdownWebPartProps {
  dataSource: 'pnp' | 'rest' | 'graph';
  defaultProductId: string;
}

const METHOD_NAMES: Record<string, string> = {
  pnp: 'PnPjs v4',
  rest: 'SPHttpClient REST',
  graph: 'Microsoft Graph'
};

export default class ListDropdownWebPart extends BaseClientSideWebPart<IListDropdownWebPartProps> {
  private _services: Record<string, IOrderService> = {};
  private _productOptions: IPropertyPaneDropdownOption[] = [];

  protected async onInit(): Promise<void> {
    await super.onInit();
    // Create each service once - never inside render or an event handler
    this._services = {
      pnp: new PnPOrderService(this.context),
      rest: new RestOrderService(this.context),
      graph: new GraphOrderService(this.context)
    };
  }

  public render(): void {
    const source: string = this.properties.dataSource || 'pnp';
    const element: React.ReactElement<IListDropdownProps> = React.createElement(ListDropdown, {
      service: this._services[source],
      methodName: METHOD_NAMES[source],
      defaultProductId: this.properties.defaultProductId ? Number(this.properties.defaultProductId) : undefined
    });
    ReactDom.render(element, this.domElement);
  }

  // Property pane dropdown bound to the same SharePoint list, loaded when the pane opens
  protected async onPropertyPaneConfigurationStart(): Promise<void> {
    if (this._productOptions.length > 0) {
      return;
    }
    this.context.statusRenderer.displayLoadingIndicator(this.domElement, 'products');
    const products = await this._services.pnp.getProducts();
    this._productOptions = products.map(p => ({ key: String(p.id), text: p.title }));
    this.context.statusRenderer.clearLoadingIndicator(this.domElement);
    this.context.propertyPane.refresh();
    this.render();
  }

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

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

  protected getPropertyPaneConfiguration(): IPropertyPaneConfiguration {
    return {
      pages: [
        {
          header: { description: 'Bind a Fluent UI Dropdown to SharePoint list items' },
          groups: [
            {
              groupName: 'Data',
              groupFields: [
                PropertyPaneDropdown('dataSource', {
                  label: 'Data method',
                  options: [
                    { key: 'pnp', text: 'PnPjs v4 (recommended)' },
                    { key: 'rest', text: 'SPHttpClient REST' },
                    { key: 'graph', text: 'Microsoft Graph' }
                  ]
                }),
                PropertyPaneDropdown('defaultProductId', {
                  label: 'Default product',
                  options: this._productOptions,
                  disabled: this._productOptions.length === 0
                })
              ]
            }
          ]
        }
      ]
    };
  }
}

How does this work?

Data method is a static dropdown that switches between the three services. Default product is bound to the SPGDemo Products list, but it loads in onPropertyPaneConfigurationStart, only when an editor opens the pane, so page visitors never pay for that request.

After the options arrive, this.context.propertyPane.refresh() redraws the pane with them. Without it, the dropdown stays empty until the editor closes and reopens the pane. Need a richer picker there? Try custom controls in the SPFx property pane.

Pro Tip: Never create the PnPjs sp object inside render() or an event handler. The PnPjs docs warn against it, and in practice you’ll see repeated requests and odd caching. Create it once in onInit.

Last, set friendly defaults in ListDropdownWebPart.manifest.json so the web part shows the PnPjs method when it’s first added:

"title": { "default": "SPG List Dropdown" },
"officeFabricIconFontName": "Dropdown",
"properties": {
  "dataSource": "pnp",
  "defaultProductId": ""
}

Test it in the SharePoint workbench with heft start

Older posts tested web parts with gulp serve. Since SPFx 1.22 the command is heft start. First, point it at your site’s workbench so it opens the page for you. Here’s config/serve.json:

{
  "$schema": "https://developer.microsoft.com/json-schemas/spfx-build/spfx-serve.schema.json",
  "port": 4321,
  "https": true,
  "initialPage": "https://{tenantDomain}/sites/SPGuides/_layouts/workbench.aspx"
}

Replace {tenantDomain} with your tenant (for example spguides.sharepoint.com). Using the site workbench instead of the root one matters here, because the web part reads lists from the SPGuides site. Now start the dev server:

heft start

Heft compiles the project, serves it on https://localhost:4321 and opens the workbench in your browser:

VS Code terminal running heft start for the SPFx list dropdown project with the local server on port 4321

In the workbench, hover over the canvas, click the + icon and pick SPG List Dropdown. The dropdowns load live data from the lists right away.

SharePoint workbench toolbox with the SPG List Dropdown web part highlighted

Open the Product dropdown and you’ll see the four items from SPGDemo Products, sorted by title. The Order dropdown stays disabled with “Pick a product first” until you choose one.

Fluent UI Product dropdown open in the SPFx web part listing the four SPGDemo Products items

I picked USB-C Dock, and the Order label switched to 53, the real count of USB-C Dock orders in the list. Filtering on Shipped left one order, SO-1002, and selecting it filled the card: Fabrikam Inc., 14 units, $1,499.88, ordered 1/28/2026, paid.

Order dropdown filtered by product and status with the selected order details card in USD

Click the pencil icon on the web part to open the property pane. Default product fills from the same list as soon as the pane opens. When I picked Wireless Mouse there, the Product dropdown on the canvas switched to it right away:

SPFx property pane with the Data method dropdown and the Default product dropdown loaded from the SharePoint list

One heads-up: Microsoft deprecated the hosted workbench on 05/13/2026 and retires it on 12/01/2026. After that, add the debug query string that heft start prints to any modern page on your site and use the SPFx Debug Toolbar instead.

Method 2: Bind the dropdown with SPHttpClient and the REST API

Use SPHttpClient when you can’t add packages, or when you’re copying a REST URL you already tested in the browser. It ships with SPFx, so there’s nothing to install beyond @microsoft/sp-http. The same client also writes data, as in SPFx CRUD operations with REST.

Here’s src/webparts/listDropdown/services/RestOrderService.ts:

import { SPHttpClient, SPHttpClientResponse } from '@microsoft/sp-http';
import { WebPartContext } from '@microsoft/sp-webpart-base';
import { IOrder, IOrderService, IProduct, ORDERS_LIST, PRODUCTS_LIST } from '../models/IOrderModels';

// Method 2: SPHttpClient + SharePoint REST API (no extra packages)
export class RestOrderService implements IOrderService {
  constructor(private _context: WebPartContext) { }

  private async _get(path: string): Promise<any> { // eslint-disable-line @typescript-eslint/no-explicit-any
    const url: string = `${this._context.pageContext.web.absoluteUrl}/_api/${path}`;
    const response: SPHttpClientResponse = await this._context.spHttpClient.get(url, SPHttpClient.configurations.v1);
    if (!response.ok) {
      throw new Error(`SharePoint returned ${response.status}: ${await response.text()}`);
    }
    return response.json();
  }

  public async getProducts(): Promise<IProduct[]> {
    const data = await this._get(`web/lists/getbytitle('${PRODUCTS_LIST}')/items?$select=Id,Title&$orderby=Title`);
    return data.value.map((i: { Id: number; Title: string }) => ({ id: i.Id, title: i.Title }));
  }

  public async getStatusChoices(): Promise<string[]> {
    const data = await this._get(`web/lists/getbytitle('${ORDERS_LIST}')/fields/getbyinternalnameortitle('OrderStatus')?$select=Choices`);
    return data.Choices;
  }

  public async getOrders(productId: number, status?: string): Promise<IOrder[]> {
    let filter: string = `ProductId eq ${productId}`;
    if (status) {
      filter += ` and OrderStatus eq '${status}'`;
    }
    const data = await this._get(`web/lists/getbytitle('${ORDERS_LIST}')/items` +
      `?$select=Id,Title,CustomerName,Quantity,OrderTotal,OrderDate,OrderStatus,Paid` +
      `&$filter=${encodeURIComponent(filter)}&$orderby=Title&$top=500`);
    return data.value.map((i: any) => ({ // eslint-disable-line @typescript-eslint/no-explicit-any
      id: i.Id,
      title: i.Title,
      customerName: i.CustomerName || '',
      quantity: i.Quantity ?? undefined,
      orderTotal: i.OrderTotal ?? undefined,
      orderDate: i.OrderDate ?? undefined,
      orderStatus: i.OrderStatus || '',
      paid: !!i.Paid
    }));
  }
}

How does this work?

this.context.spHttpClient.get() sends the request with the current user’s sign-in, and SPHttpClient.configurations.v1 sets the headers SharePoint expects. The JSON comes back with the items in a value array.

The URLs are the same REST endpoints you’d use anywhere, for example _api/web/lists/getbytitle('SPGDemo Products')/items?$select=Id,Title. So here’s the catch: the $filter text must be URL-encoded, which is why the code wraps it in encodeURIComponent(). Odd JSON errors from REST calls usually mean a wrong header; I explain one in the StartObject node error in SPFx.

When I switched the property pane to SPHttpClient REST, the web part showed the same four products, the same four statuses and the same order counts. That’s the point of the shared contract: only the service changed.

Method 3: Bind the dropdown with Microsoft Graph (MSGraphClientV3)

Use Microsoft Graph when the same component also reads Teams, users or files, or when the list lives on another site. MSGraphClientV3 handles the token for you. I use the same client in the SPFx user profile web part with Microsoft Graph.

Here’s src/webparts/listDropdown/services/GraphOrderService.ts:

import { MSGraphClientV3 } from '@microsoft/sp-http';
import { WebPartContext } from '@microsoft/sp-webpart-base';
import { IOrder, IOrderService, IProduct, ORDERS_LIST, PRODUCTS_LIST } from '../models/IOrderModels';

// Method 3: Microsoft Graph through MSGraphClientV3 (needs Sites.Read.All approved for SPFx)
export class GraphOrderService implements IOrderService {
  constructor(private _context: WebPartContext) { }

  // Graph site id = "{hostname},{site collection id},{web id}"
  private get _siteId(): string {
    const page = this._context.pageContext;
    return `${new URL(page.web.absoluteUrl).hostname},${page.site.id.toString()},${page.web.id.toString()}`;
  }

  private async _client(): Promise<MSGraphClientV3> {
    return this._context.msGraphClientFactory.getClient('3');
  }

  public async getProducts(): Promise<IProduct[]> {
    const client = await this._client();
    const res = await client
      .api(`/sites/${this._siteId}/lists/${encodeURIComponent(PRODUCTS_LIST)}/items`)
      .expand('fields($select=Title)')
      .get();
    return res.value
      .map((i: { id: string; fields: { Title: string } }) => ({ id: Number(i.id), title: i.fields.Title }))
      .sort((a: IProduct, b: IProduct) => a.title.localeCompare(b.title));
  }

  public async getStatusChoices(): Promise<string[]> {
    const client = await this._client();
    const res = await client
      .api(`/sites/${this._siteId}/lists/${encodeURIComponent(ORDERS_LIST)}/columns`)
      .select('name,choice')
      .get();
    const column = res.value.find((c: { name: string }) => c.name === 'OrderStatus');
    return column.choice.choices;
  }

  public async getOrders(productId: number, status?: string): Promise<IOrder[]> {
    let filter: string = `fields/ProductLookupId eq '${productId}'`;
    if (status) {
      filter += ` and fields/OrderStatus eq '${status}'`;
    }
    const client = await this._client();
    const res = await client
      .api(`/sites/${this._siteId}/lists/${encodeURIComponent(ORDERS_LIST)}/items`)
      // Product and OrderStatus aren't indexed, so Graph needs this header to filter on them
      .header('Prefer', 'HonorNonIndexedQueriesWarningMayFailRandomly')
      .expand('fields($select=Title,CustomerName,Quantity,OrderTotal,OrderDate,OrderStatus,Paid)')
      .filter(filter)
      .top(500)
      .get();
    return res.value
      .map((i: any) => ({ // eslint-disable-line @typescript-eslint/no-explicit-any
        id: Number(i.id),
        title: i.fields.Title,
        customerName: i.fields.CustomerName || '',
        quantity: i.fields.Quantity ?? undefined,
        orderTotal: i.fields.OrderTotal ?? undefined,
        orderDate: i.fields.OrderDate ?? undefined,
        orderStatus: i.fields.OrderStatus || '',
        paid: !!i.fields.Paid
      }))
      .sort((a: IOrder, b: IOrder) => a.title.localeCompare(b.title));
  }
}

How does this work?

Graph needs a site ID, not a URL. The code builds it from the page context as hostname,site collection ID,web ID, so it works on any site without a lookup call. I show other ways to read site details in getting SharePoint site information with Microsoft Graph.

Item columns come back inside fields, and expand('fields($select=...)') limits them. Lookup columns show up as ProductLookupId, and choice columns are read from the list’s columns endpoint.

So here’s the catch: Product and OrderStatus aren’t indexed, and Graph refuses to filter on non-indexed columns unless you send the Prefer: HonorNonIndexedQueriesWarningMayFailRandomly header. On big lists, index the column instead.

Graph also needs permission. Add this to config/package-solution.json under solution:

"webApiPermissionRequests": [
  {
    "resource": "Microsoft Graph",
    "scope": "Sites.Read.All"
  }
],

In my tenant, Sites.Read.All was already approved for SharePoint Online Web Client Extensibility, so Graph worked straight from the workbench. Wireless Mouse returned 52 orders, and filtering on Processing left SO-1106 for Coho Winery ($479.92, ordered 1/22/2026, not paid).

SPFx web part in the SharePoint workbench switched to the Microsoft Graph data method with the same dropdown options

Package the solution

When the dropdowns work in the workbench, stop heft start (Ctrl+C) and build the production package:

npm run build

The generated script runs heft test --clean --production and then heft package-solution --production. It ends with sharepoint/solution/spg-list-dropdown.sppkg. You can ship more than one web part in the same package; see adding multiple web parts to one SPFx solution.

VS Code terminal with npm run build finished and spg-list-dropdown.sppkg created

That file is ready to ship: upload the .sppkg to the app catalog when you’re ready, following Microsoft Learn deployment steps, and have an admin approve the Graph request in API access if you use Method 3. If you’ve never deployed a web part, building your first SPFx web part walks through the basics.

Which method should you use?

PnPjs v4SPHttpClient RESTMicrosoft Graph
Extra package@pnp/spNoneNone (sp-http)
Admin approvalNoNoYes, Sites.Read.All
Code sizeSmallestMedium (URLs, JSON)Medium (site ID, fields)
Filter non-indexed columnsYesYesOnly with the Prefer header
Best forMost web partsNo-dependency projectsCross-site or Microsoft 365 data

My pick is PnPjs for anything that lives on one SharePoint site. If you need type-ahead search over many items, a dropdown gets long fast: switch to the Fluent UI ComboBox control in SPFx.

Things to Keep in Mind

  • Large lists: a dropdown with hundreds of options isn’t usable. Filter on the server (like the product filter here) or use a ComboBox with search.
  • Blank values: rows like SO-1001 have no product, quantity or date. Map them to undefined and show a dash, or the details card prints “null”.
  • Lookup filters: filter on ProductId in PnPjs and REST, and on fields/ProductLookupId in Graph. Filtering on Product itself fails.
  • Choice values: read them from the field’s Choices, never hard-code them. A new status then appears without a redeploy.
  • Graph 403 errors: the request in package-solution.json does nothing until an admin approves it in the SharePoint admin center under Advanced > API access.

Building the same dropdown inside a list form instead of a page? My Fluent UI dropdown in an SPFx Form Customizer post covers that case, and the SPFx cascading dropdown tutorial goes deeper on parent-child dropdowns.

Want the finished project instead of typing it? You’ll find it with our other ready-made solutions on the Power Platform and SPFx solutions page.

A few more SPFx guides that pair well with this one:

Frequently Asked Questions

Is sp-pnp-js still supported in SPFx?

No. sp-pnp-js is deprecated on npm and points to the newer @pnp packages. Use PnPjs v4 with spfi().using(SPFx(this.context)), as shown in the PnPjs getting started guide.

What replaces import pnp from ‘sp-pnp-js’?

Import spfi and SPFx from @pnp/sp, add the selective imports @pnp/sp/webs, @pnp/sp/lists and @pnp/sp/items, and create one sp instance in onInit. Then call sp.web.lists.getByTitle(‘List’).items().

How do I bind a choice column to a Fluent UI Dropdown in SPFx?

Read the field’s Choices property, for example with PnPjs fields.getByInternalNameOrTitle(‘OrderStatus’).select(‘Choices’)(), and map each choice to { key: choice, text: choice }.

Can I use SPHttpClient instead of PnPjs?

Yes. Call this.context.spHttpClient.get() with the _api/web/lists/getbytitle(…)/items URL and SPHttpClient.configurations.v1, then map response.value to dropdown options. It needs no extra package.

Which permission does Microsoft Graph need to read list items?

Sites.Read.All is the least privileged delegated permission for listing items. Request it in package-solution.json, and a SharePoint admin approves it in the SharePoint admin center under Advanced > API access.