How to use office UI fabric react groupedlist in SPFx web part

In this SPFx tutorial, we will discuss how to use office UI fabric react groupedlist in an SPFx client-side web part.

We will see step by step how to create a client-side web part using SharePoint framework and then we will see how to use the office UI fabric react groupedlist.

If you are new to SPFx, then I hope you have already set up the development environment for SharePoint Framework. And also, you can check how to create a client-side web part using SPFx.

SPFx office ui fabric react groupedlist example

Here, we are going to create something like the below. It will display a list of icons and when the user clicks on the arrow, it will display text.

office ui fabric groupedlist
office ui fabric groupedlist

Here the items we are going to read from the below SharePoint list. Here you can see, the icons are coming from the IconCategory column and the text is appearing from the Title column.

fabric ui groupedlist
fabric ui groupedlist

Now, let us see how to create a SPFx client side web part.

Open the nodejs command prompt and then create a directory in a location where you want to save the files.

md FabricUIGroupedListwithIcons

cd FabricUIGroupedListwithIcons

Then run the below command to start creating the spfx client side web part.

yo @microsoft/sharepoint

It will ask you the below things:

  • What is your solution name? Click on Enter to take the default name.
  • Which baseline packages do you want to target for your component (s)? Here choose one from the below options:
    • SharePoint Online only (latest)
    • SharePoint 2016 onwards, including 2019 and SharePoint Online
    • SharePoint 2019 onwards, including SharePoint Online

Here select SharePoint Online only (latest).

  • Where do you want to place the files? Choose one from the following:
    • Use the current folder
    • Create a subfolder with solution name
See also  type 'string' is not assignable to type 'number'.ts

Here choose Use the current folder.

  • Do you to allow the tenant admin the choice of being able to deploy the solution to all sites immediately without running any feature deployment or adding apps in sites? Choose N.
  • Will the components in the solution require permissions to access web APIs that are unique and not shared with other components in the tenant? Choose N.
  • Which type of client-side component to create? Choose WebPart from the below options:
    • WebPart
    • Extension
    • Library
  • What is your web part name? Give FabricUiGroupedList as the web part name
  • What is your web part description? Click on Enter to take the default name.
  • Which framework would you like to use? Choose React from the below options:
    • No JavaScript framework
    • React
    • Knockout

Then it will take sometime and then you can see a successful message that the solution got created.

Then run the below command to open the solution using visual studio code.

code .

The solution looks like below:

office ui fabric groupedlist examples
office ui fabric groupedlist examples

Here Open the IFabricUiGroupedListProps.ts file, and add the below property (SiteURL).

export interface IFabricUiGroupedListProps {
  description: string;
  SiteURL:any;
}

Then open the FabricUiGroupedListWebPart.ts file and pass the values to the SiteURL property like below in the render() method.

public render(): void {
    const element: React.ReactElement<IFabricUiGroupedListProps> = React.createElement(
      FabricUiGroupedList,
      {
        description: this.properties.description,
        SiteURL:this.context.pageContext.web.absoluteUrl
      }
    );

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

Now, we need to add the code in the FabricUiGroupedList.tsx file (react component file).

The completely code looks like below:

import * as React from 'react';
import styles from './FabricUiGroupedList.module.scss';
import { Icon, initializeIcons } from "office-ui-fabric-react";
import { Selection, SelectionMode } from 'office-ui-fabric-react/lib/Selection';
import { GroupedList, IGroup, IGroupRenderProps, IGroupHeaderProps, GroupHeader } from 'office-ui-fabric-react/lib/GroupedList';
import { IFabricUiGroupedListProps } from './IFabricUiGroupedListProps';
import { escape, groupBy, findIndex } from '@microsoft/sp-lodash-subset';

export interface GroupedListStates {
  items: IDocument[];
  result: any;

}

export interface IDocument {
  Title: any;
  IconCategory: any;
}

export default class FabricUiGroupedList extends React.Component<IFabricUiGroupedListProps, GroupedListStates> {
  private _selection: Selection;
  constructor(props) {

    super(props);
    initializeIcons();
    this.state = {
      items: [],
      result: [],
    };
  }
  public async componentWillMount() {
    let groupedlistitems = await GetGroupedListData(this.props.SiteURL);
    console.log(groupedlistitems);
    this.setState({ result: groupedlistitems });

  }

  private _generateIGroupsFromArray(sortedItems: any[]): IGroup[] {
    const groupedByIconCategory: any = groupBy(sortedItems, (i: any) => i.IconCategory);
    let groups: IGroup[] = [];
    for (const IconCategory in groupedByIconCategory) {
      groups.push({
        name: IconCategory,
        key: IconCategory,
        startIndex: findIndex(sortedItems, (i: any) => i.IconCategory === IconCategory),
        count: groupedByIconCategory[IconCategory].length,
         isCollapsed:findIndex(sortedItems, (i: any) => i.IconCategory === IconCategory)==0? false:true
      });
    }
    return groups;
  }
  public render(): React.ReactElement<IFabricUiGroupedListProps> {
    return (
      <div>
        <h3>Fabric UI Grouped List with Icon Category</h3>
        <hr />
        <GroupedList
          className={styles.groupcolor}
          items={this.state.result}
          onRenderCell={this._onRenderCell}
          groups={this._generateIGroupsFromArray(this.state.result)}
          groupProps={groupedListProps}
          selection={this._selection}
          selectionMode={SelectionMode.none}
        />
      </div>

    );
  }

  private _onRenderCell = (_nestingDepth: number, item: IDocument, itemIndex: number): JSX.Element => {
    return (
      <div>
        <span style={{ fontSize: "large", paddingLeft: "25px" }}>
          {item.Title}</span>
        <br />
      </div>

    );
  }
}

export const GetGroupedListData = async (webURL) => {
  let items = [];
  await fetch(`${webURL}/_api/web/lists/Getbytitle('FabricUIGroupedList')/items`, {
    method: 'GET',
    mode: 'cors',
    credentials: 'include',
    headers: new Headers({
      'Content-Type': 'application/json',
      'Accept': 'application/json',
      'Access-Control-Allow-Origin': '*',
      'Cache-Control': 'no-cache',
      'pragma': 'no-cache',
    }),
  }).then(async (response) => await response.json())
    .then(async (data) => {
      console.log(data);
      if (data.value.length > 0) {
        for (let i = 0; i < data.value.length; i++) {
          items.push({
            Title: data.value[i].Title,
            IconCategory: data.value[i].IconCategory,

          });
        }
      }
    }).catch(error => console.error(error));
  return await items;
};

const onRenderHeader = (props?: IGroupHeaderProps): JSX.Element | null => {

  if (props) {
    const toggleCollapse = (): void => {
      props.onToggleCollapse!(props.group!);
    };
    return (
      <div>
        <Icon style={{marginBottom:"10px", fontSize: 25, cursor: "pointer" }} iconName={"ChevronRightSmall"} onClick={toggleCollapse}></Icon>
        <Icon
          style={{ paddingLeft: "16px", fontSize: 37, cursor: "pointer" }} iconName={props.group.name}
          onClick={toggleCollapse}
        >
          {props.group!.isCollapsed ? 'Expand' : 'Collapse'}
        </Icon>

      </div>
    );
  }

  return null;
};

const groupedListProps = {
  onRenderHeader
};

Now run the below command to open the local workbench.

gulp serve

While the local workbench is running open the SharePoint workbench and add the web part.

https://tsinfotechnologies.sharepoint.com/sites/SPFxForBlog/_layouts/15/workbench.aspx

In the SharePoint workbench, add the web part and it will looks like below:

See also  Difference between SharePoint list and Document library
office ui fabric react groupedlist example
office ui fabric react groupedlist example

If you want to deploy the web part to the SharePoint environment, then run the below commands.

gulp bundle --ship

gulp package-solution --ship

Once you run the above command, it will create the .sppkg file under the SharePoint folder.

Simply, upload this file into the tenant app catalog site or SharePoint site collection app catalog site. Then you can add the web part into a modern web part page in SharePoint Online.

Download SPFx office ui fabric react groupedlist Solution

Unzip the solution and run the below command:

npm i

You may like the following SPFx tutorials:

In this tutorial, we learned an example on office ui fabric react groupedlist. We saw how to use the office ui fabric react groupedlist in a SharePoint framework client side web part.

>