List View in Spfx

Introduction

 
Listview-control is a react control provider by @pnp/spfx-controls-react. In this article, I am using the PnpV2 library for consuming Sharepoint operations.
 

Steps 

 
Open a command prompt and create a directory for the SPFx solution.
 
md spfx-SpfxListView
 
Navigate to the above created directory.
 
cd spfx-SpfxListView
 
Run the Yeoman SharePoint Generator to create the solution.
 
yo @microsoft/sharepoint
 
Solution Name
 
Hit Enter for the default name (spfx-SpfxListView in this case) or type in any other name for your solution.
Selected choice - Hit Enter
 
Target for the component
 
Here, we can select the target environment where we are planning to deploy the client web part; i.e., SharePoint Online or SharePoint OnPremise (SharePoint 2016 onwards).
Selected choice - SharePoint Online only (latest).
 
Place of files
 
We may choose to use the same folder or create a subfolder for our solution.
Selected choice - same folder.
 
Deployment option
 
Selecting Y will allow the app to be deployed instantly to all sites and be accessible everywhere.
Selected choice - N (install on each site explicitly).
 
Permissions to access web APIs
 
Choose if the components in the solution require permission to access web APIs that are unique and not shared with other components in the tenant.
Selected choice - N (solution contains unique permissions)
 
Type of client-side component to create
 
We can choose to create a client-side web part or an extension. Choose the web part option.
Selected choice - WebPart
 
Web part name
 
Hit Enter to select the default name or type in any other name.
Selected choice - SpfxListView
 
Web part description
 
Hit Enter to select the default description or type in any other value.
 
Framework to use
 
Select any JavaScript framework to develop the component. Available choices are - No JavaScript Framework, React, and Knockout.
Selected choice - React
 
The Yeoman generator will perform a scaffolding process to generate the solution. The scaffolding process will take a significant amount of time.
 
Once the scaffolding process is completed, lock down the version of project dependencies by running the below command:
 
npm shrinkwrap
 
In the command prompt, type the below command to open the solution in the code editor of your choice.
 
NPM Packages used:
  1. npm install @pnp/spfx-controls-react --save --save-exact  //for pnp reusuable controls  
Once the package is installed, you will have to configure the resource file of the property controls to be used in your project. You can do this by opening the config/config.json and adding the following line to the localizedResources property:
  1. "ControlStrings""node_modules/@pnp/spfx-controls-react/lib/loc/{locale}.js"    
 Since v1.4.0 the localized resource path will automatically be configured during the dependency installing.
  1. npm install @pnp/[email protected] --save  //for sharepoint operations      
  2. npm install @pnp/polyfill-ie11 --save  //for iell support     

Conclusion 

 
In this article, I introduced a new way to consume SharePoint operations using writing a separate service (Reusable methods)
 
In SpfxService.ts.
  1. import "@pnp/polyfill-ie11";    
  2. import {sp} from '@pnp/sp/presets/all';    
  3. import {WebPartContext}  from '@microsoft/sp-webpart-base';    
  4. import {PageContext}  from '@microsoft/sp-page-context';    
  5. export interface IListitem {      
  6.     Title: string;     
  7.     Region:string;    
  8.   }     
  9.   export  class SpfxService{    
  10.     constructor(context:WebPartContext,mypagecontext:PageContext){    
  11.     sp.setup({    
  12.         spfxContext:context,    
  13.         sp: {    
  14.             headers: {    
  15.               "Accept""application/json; odata=verbose"    
  16.             }    
  17.           },    
  18.           ie11: true    
  19.             
  20.     });    
  21.         
  22.     }    
  23.     public async getAllrecords(listname:string):Promise<IListitem[]>{    
  24.         const result:IListitem[]=[];    
  25.         return new Promise<IListitem[]>(async(resolve, reject)=>{    
  26.     sp.web.lists.getByTitle(listname).items.getAll().then((items)=>{    
  27.         items.map((item)=>{    
  28.     result.push({Title:item.Title,Region:item.Region});    
  29.         });    
  30.         resolve(result);    
  31.     });    
  32.         
  33.         
  34.         });    
  35.     }}    
In ISpfxListViewProps.ts
  1. import { WebPartContext } from "@microsoft/sp-webpart-base";    
  2.     
  3. export interface ISpfxListViewProps {    
  4.   description: string;    
  5.   context:WebPartContext;    
  6. }    
In SpfxListViewWebPart.ts
  1. import * as React from 'react';    
  2. import * as ReactDom from 'react-dom';    
  3. import { Version } from '@microsoft/sp-core-library';    
  4. import {    
  5.   IPropertyPaneConfiguration,    
  6.   PropertyPaneTextField    
  7. } from '@microsoft/sp-property-pane';    
  8. import { BaseClientSideWebPart } from '@microsoft/sp-webpart-base';    
  9. import * as strings from 'SpfxListViewWebPartStrings';    
  10. import SpfxListView from './components/SpfxListView';    
  11. import { ISpfxListViewProps } from './components/ISpfxListViewProps';    
  12.     
  13. export interface ISpfxListViewWebPartProps {    
  14.   description: string;    
  15. }    
  16.     
  17. export default class SpfxListViewWebPart extends BaseClientSideWebPart <ISpfxListViewWebPartProps> {    
  18.   public render(): void {    
  19.     const element: React.ReactElement<ISpfxListViewProps> = React.createElement(    
  20.       SpfxListView,    
  21.       {    
  22.         description: this.properties.description,    
  23.         context:this.context    
  24.       }    
  25.     );    
  26.     
  27.     ReactDom.render(element, this.domElement);    
  28.   }    
  29.     
  30.   protected onDispose(): void {    
  31.     ReactDom.unmountComponentAtNode(this.domElement);    
  32.   }    
  33.     
  34.   protected get dataVersion(): Version {    
  35.     return Version.parse('1.0');    
  36.   }    
  37.     
  38.   protected getPropertyPaneConfiguration(): IPropertyPaneConfiguration {    
  39.     return {    
  40.       pages: [    
  41.         {    
  42.           header: {    
  43.             description: strings.PropertyPaneDescription    
  44.           },    
  45.           groups: [    
  46.             {    
  47.               groupName: strings.BasicGroupName,    
  48.               groupFields: [    
  49.                 PropertyPaneTextField('description', {    
  50.                   label: strings.DescriptionFieldLabel    
  51.                 })    
  52.               ]    
  53.             }    
  54.           ]    
  55.         }    
  56.       ]    
  57.     };    
  58.   }    
  59. }    
In SpfxListView.tsx
  1. import * as React from 'react';    
  2. import { ISpfxListViewProps } from './ISpfxListViewProps';    
  3. import { ListView, IViewField, SelectionMode, GroupOrder, IGrouping } from "@pnp/spfx-controls-react/lib/ListView";    
  4. import {SpfxService }from './SpfxService';    
  5. interface IPnpstate {        
  6.   ListData:IListitem[];      
  7. }      
  8. export interface IListitem {      
  9.   Title: string;      
  10.   Region:string;     
  11. }     
  12.     
  13. export default class SpfxListView extends React.Component<ISpfxListViewProps,IPnpstate> {    
  14.   private _SPfxService:SpfxService;    
  15.   constructor(props: ISpfxListViewProps, state: IPnpstate) {      
  16.     super(props);      
  17.     this.state = {      
  18.       ListData: []      
  19.     };      
  20.     this._SPfxService =new SpfxService(this.props.context,this.props.context.pageContext);    
  21.   }    
  22.   private _getSelection(items: any[]) {    
  23.     console.log('Selected items:', items);    
  24.   }    
  25.       
  26.   public componentDidMount(){    
  27.     this._SPfxService.getAllrecords("ListView").then((result:IListitem[]) =>{    
  28.       this.setState({ ListData: result });      
  29.     
  30.     });    
  31. }    
  32.   public render(): React.ReactElement<ISpfxListViewProps> {    
  33.     return (    
  34.       <div >    
  35. <ListView    
  36.   items={this.state.ListData}    
  37.   showFilter={true}    
  38.   filterPlaceHolder="Search..."    
  39.   compact={true}    
  40.   selectionMode={SelectionMode.multiple}    
  41.   selection={this._getSelection}    
  42.   groupByFields={groupByFields}    
  43.   viewFields={viewFields} />    
  44.       </div>    
  45.     );    
  46.   }    
  47. }    
  48. const groupByFields: IGrouping[] = [    
  49.  {    
  50.     name: "Region",     
  51.     order: GroupOrder.descending    
  52.   }    
  53. ];    
  54. export const  viewFields : IViewField []= [{    
  55.   name: "Title",    
  56.   displayName: "MyTitle",    
  57.   //linkPropertyName: "c",    
  58.   isResizable: true,    
  59.   sorting: true,    
  60.   minWidth: 0,    
  61.   maxWidth: 150    
  62. },{    
  63.   name: "Region",    
  64.   displayName: "MyRegion",    
  65.   linkPropertyName: "c",    
  66.   isResizable: true,    
  67.   sorting: true,    
  68.   minWidth: 0,    
  69.   maxWidth: 100    
  70. },];    
Here, I am using list name as ListView, Title, and Region as single line of text.
 
Properties for ListView control
  • iconFieldName - Specify the items' property name that defines the file URL path which will be used to show the file icon. This automatically creates a column and renders the file icon.
  • Items - Items to render in the list view.
  • viewFields - The fields you want to render in the list view. Check the IViewField implementation to see which properties you can define.
  • Compact - Boolean value to indicate if the control should render in compact mode. By default this is set to false.
  • selectionMode - Specify if the items in the list view can be selected and how. Options are: none, single, multi.
  • Selection - Selection event that passes the selected item(s) from the list view.
  • groupByFields - Defines the field on which you want to group the items in the list view.
  • defaultSelection - The index of the items to be select by default
  • filterPlaceHolder - Specify the placeholder for the filter text box. Default 'Search'
  • showFilter - Specify if the filter text box should be rendered.
  • defaultFilter - Specify the initial filter to be applied to the list.
Properties for ListView control IViewField
  • name - Name of the field.
  • displayName - Name that will be used as the column title. If not defined, the name property will be used.
  • linkPropertyName - Specify the field name that needs to be used to render a link for the current field.
  • sorting - Specify if you want to enable sorting for the current field.
  • minWidth - Specify the minimum width of the column.
  • maxWidth - Specify the maximum width of the column.
  • isResizable - Determines if the column can be resized.
  • render - Override how the field has to get rendered.
Expected output
 
With Grouping
 
 
 
Without Grouping
 
 

Conclusion

 
In this article, we learned how to implement ListView in SPFX webpart. I hope this helps someone. Happy coding :)