Displaying a SharePoint List using Fluent UI in SPFx

When developing for SharePoint using the SharePoint Framework (SPFx), you often need to fetch data from a SharePoint list and display it in a user-friendly manner. One of the most powerful ways to achieve this is by using Fluent UI, a collection of UI components that follows the Microsoft design principles.

In this article, I will guide you through the process of displaying items from a SharePoint list using Fluent UI within an SPFx web part. The article covers:

  1. Setting up the SPFx Environment.
  2. Fetching Data from the SharePoint List using PnPjs.
  3. Rendering Data with Fluent UI’s DetailsList.

Let’s get started.

1. Setting Up the SPFx Environment

Before diving into the code, make sure you have the following prerequisites installed:

  • Node.js
  • Yeoman and the SPFx Generator

To create a new SPFx project, run the following command:

yo @microsoft/sharepoint

Follow the prompts to configure the web part. Once the project is generated, we need to install Fluent UI and PnPjs to help us fetch and display the data from the SharePoint list.

npm install @fluentui/react @pnp/sp

2. Fetching Data from the SharePoint List using PnPjs

PnPjs is a library that simplifies working with the SharePoint REST API. Here’s how to integrate PnPjs into your SPFx project:

  1. In your main web part file (PnPGetStartList2WebPart.ts), import the necessary modules from PnPjs and configure it to use the SharePoint context.
   import { spfi, SPFx } from "@pnp/sp";
   import "@pnp/sp/webs";
   import "@pnp/sp/lists";
   import "@pnp/sp/items";

   export default class PnPGetStartList2WebPart extends BaseClientSideWebPart<IPnPGetStartList2Props> {
     private _sp: SPFI;

     protected onInit(): Promise<void> {
       this._sp = spfi().using(SPFx(this.context));
       return super.onInit();
     }

     public render(): void {
       this._getListItems();
     }

     private async _getListItems(): Promise<void> {
       try {
         const items = await this._sp.web.lists.getByTitle("YourListName").items();
         console.log(items); // For debugging purposes
       } catch (error) {
         console.error("Error fetching list items", error);
       }
     }
   }

In this example, spfi() initializes the PnPjs client and getByTitle("YourListName") retrieves the list items. You can replace "YourListName" with the name of the SharePoint list you want to fetch data from.

3. Rendering Data with Fluent UI’s DetailsList

Next, we’ll use Fluent UI’s DetailsList component to display the data. First, ensure you’ve imported the necessary Fluent UI components.

  1. Import the DetailsList and define the columns for your table.
   import * as React from 'react';
   import { DetailsList, IColumn } from '@fluentui/react/lib/DetailsList';

   export interface IListItem {
     Title: string;
     ID: number;
     // Add more fields as needed
   }

   export default class PnPGetStartList2WebPart extends BaseClientSideWebPart<IPnPGetStartList2Props> {
     private _columns: IColumn[] = [
       { key: 'column1', name: 'Title', fieldName: 'Title', minWidth: 100, maxWidth: 200, isResizable: true },
       { key: 'column2', name: 'ID', fieldName: 'ID', minWidth: 50, maxWidth: 100, isResizable: true },
     ];

     private async _getListItems(): Promise<IListItem[]> {
       try {
         const items = await this._sp.web.lists.getByTitle("YourListName").items.select("Title", "ID")();
         return items;
       } catch (error) {
         console.error("Error fetching list items", error);
         return [];
       }
     }

     public async render(): Promise<void> {
       const items: IListItem[] = await this._getListItems();

       const element: React.ReactElement = React.createElement(
         DetailsList,
         {
           items: items,
           columns: this._columns,
           setKey: 'set',
           layoutMode: 0,
           selectionMode: 0,
         }
       );

       ReactDom.render(element, this.domElement);
     }
   }
  1. Explanation:
    • DetailsList: This Fluent UI component is used to render a table-like structure. We pass the items (from the list) and columns (defined in the _columns array) as props.
    • IListItem: This interface defines the structure of the list items we fetch from SharePoint.
    • Columns: In this example, we’re displaying the Title and ID fields. You can modify this to match the columns of your list.

Testing the Web Part

  1. Deploy your solution by running:
   gulp serve
  1. Open the SharePoint Workbench, either online or locally, to add the web part to a test page.

Once the web part is loaded, it will fetch the data from the specified list and render it in a table using Fluent UI’s DetailsList component.

Conclusion

With Fluent UI and PnPjs, displaying data from a SharePoint list in an SPFx web part becomes much easier and highly customizable. The DetailsList component allows for flexible rendering of list items, and PnPjs simplifies the interaction with SharePoint data.

Summary of Key Steps:

  1. Create an SPFx Web Part:
   yo @microsoft/sharepoint
  1. Install Fluent UI and PnPjs:
   npm install @fluentui/react @pnp/sp
  1. Initialize PnPjs:
   this._sp = spfi().using(SPFx(this.context));
  1. Fetch SharePoint List Items:
   const items = await this._sp.web.lists.getByTitle("YourListName").items();
  1. Render List Items with Fluent UI:
   <DetailsList items={items} columns={this._columns} />

By following this guide, you’ll be able to create dynamic and visually appealing web parts that effectively display data from SharePoint lists.

Edvaldo Guimrães Filho Avatar

Published by

Categories:

Leave a comment