Building a SharePoint Grid using Fluent UI and PnPjs

In this article, we will walk through how to create a grid that displays SharePoint list data using Fluent UI’s DetailsList component, while fetching the data using PnPjs. By the end, you’ll understand how these tools work together to provide a flexible and scalable solution.

1. Introduction to Fluent UI and PnPjs

Fluent UI is a React-based component library developed by Microsoft to create consistent user interfaces across Microsoft 365 products. The DetailsList component, one of Fluent UI’s core components, is perfect for rendering tabular data.

PnPjs (Patterns and Practices JavaScript Library) simplifies interaction with SharePoint by providing an easy-to-use API to perform operations like reading from SharePoint lists, updating items, etc.

2. Prerequisites

Before you get started, make sure you have the following:

  • SharePoint Online environment
  • Node.js installed
  • SharePoint Framework (SPFx) environment setup
  • Basic understanding of React

3. Setting up the Project

First, create a SharePoint Framework project using the Yeoman generator.

yo @microsoft/sharepoint

Follow the prompts to configure the project, ensuring that you choose React as the framework. Once the project is generated, install the required libraries for Fluent UI and PnPjs:

npm install @pnp/sp @pnp/logging @pnp/common @pnp/odata @fluentui/react

4. Adding PnPjs and Fluent UI to the Web Part

  1. Initialize PnPjs:
    In your web part’s main file (e.g., MyWebPart.ts), initialize PnPjs to work with the current SharePoint context.
import { sp } from "@pnp/sp";
import "@pnp/sp/webs";
import "@pnp/sp/lists";
import "@pnp/sp/items";

export default class MyWebPart extends BaseClientSideWebPart<IMyWebPartProps> {

  public onInit(): Promise<void> {
    return super.onInit().then(_ => {
      sp.setup({
        spfxContext: this.context
      });
    });
  }
}
  1. Fetching SharePoint Data:
    In your React component, use PnPjs to fetch data from a SharePoint list. You can use sp.web.lists.getByTitle to retrieve list items.
import * as React from 'react';
import { sp } from '@pnp/sp/presets/all';
import { DetailsList, IColumn } from '@fluentui/react';

const MyGridComponent: React.FC = () => {
  const [items, setItems] = React.useState<any[]>([]);

  // Define the columns for your grid
  const columns: IColumn[] = [
    { key: 'column1', name: 'Title', fieldName: 'Title', minWidth: 100, maxWidth: 200, isResizable: true },
    { key: 'column2', name: 'Created By', fieldName: 'Author', minWidth: 100, maxWidth: 200, isResizable: true },
    { key: 'column3', name: 'Created', fieldName: 'Created', minWidth: 100, maxWidth: 200, isResizable: true },
  ];

  // Fetch data from SharePoint list
  React.useEffect(() => {
    const fetchItems = async () => {
      const listItems = await sp.web.lists.getByTitle("MyList").items.select("Title", "Author/Title", "Created").expand("Author")();
      setItems(listItems);
    };
    fetchItems();
  }, []);

  return (
    <DetailsList
      items={items}
      columns={columns}
      setKey="set"
      layoutMode={DetailsListLayoutMode.justified}
      selectionPreservedOnEmptyClick={true}
      onItemInvoked={item => alert(`Item invoked: ${item.Title}`)}
    />
  );
};

export default MyGridComponent;

5. Key Components in the Code

  • Columns Definition: The IColumn[] defines the structure of the grid. Each column specifies what field to display and whether it’s resizable.
  • Fetching Data: In the useEffect hook, we use PnPjs’s sp.web.lists.getByTitle method to fetch items from the SharePoint list named “MyList.” The fields are selected and expanded for related properties like the “Author” field.
  • Rendering the Grid: The DetailsList component is used to render the data fetched from SharePoint in a tabular format.

6. Handling Complex Data

If your list contains complex fields like lookup columns or user fields (e.g., Author is a user lookup field), you’ll need to use the expand functionality in PnPjs to retrieve the related data.

const listItems = await sp.web.lists.getByTitle("MyList").items
  .select("Title", "Author/Title", "Created")
  .expand("Author")(); // This expands the Author field to retrieve user details

In this case, you would use item.Author.Title to display the author’s name in the grid.

7. Advanced Features

You can further enhance the grid by adding features such as:

  • Sorting: Enable sorting by columns.
  • Filtering: Add a search box to filter the grid data.
  • Pagination: Implement pagination if your list contains many items.

8. Conclusion

By integrating Fluent UI’s DetailsList with PnPjs, you can create powerful and customizable data grids for SharePoint. This combination allows you to fetch SharePoint list data and present it in a user-friendly, responsive table that can be extended with additional features such as filtering, sorting, and pagination.

9. Summary of Commands

Here’s a quick summary of the commands you’ll need:

CommandDescription
sp.web.lists.getByTitle("MyList").items.select("Title")Fetches SharePoint list items with the “Title” field
expand("Author")Expands a lookup/user field to retrieve additional details
DetailsListRenders a grid using Fluent UI

Edvaldo Guimrães Filho Avatar

Published by

Categories:

Leave a comment