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:
- npm install @pnp/spfx-controls-react --save --save-exact
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:
- "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.
Conclusion
In this article, I introduced a new way to consume SharePoint operations using writing a separate service (Reusable methods)
In SpfxService.ts.
- import "@pnp/polyfill-ie11";
- import {sp} from '@pnp/sp/presets/all';
- import {WebPartContext} from '@microsoft/sp-webpart-base';
- import {PageContext} from '@microsoft/sp-page-context';
- export interface IListitem {
- Title: string;
- Region:string;
- }
- export class SpfxService{
- constructor(context:WebPartContext,mypagecontext:PageContext){
- sp.setup({
- spfxContext:context,
- sp: {
- headers: {
- "Accept": "application/json; odata=verbose"
- }
- },
- ie11: true
-
- });
-
- }
- public async getAllrecords(listname:string):Promise<IListitem[]>{
- const result:IListitem[]=[];
- return new Promise<IListitem[]>(async(resolve, reject)=>{
- sp.web.lists.getByTitle(listname).items.getAll().then((items)=>{
- items.map((item)=>{
- result.push({Title:item.Title,Region:item.Region});
- });
- resolve(result);
- });
-
-
- });
- }}
In ISpfxListViewProps.ts
- import { WebPartContext } from "@microsoft/sp-webpart-base";
-
- export interface ISpfxListViewProps {
- description: string;
- context:WebPartContext;
- }
In SpfxListViewWebPart.ts
- import * as React from 'react';
- import * as ReactDom from 'react-dom';
- import { Version } from '@microsoft/sp-core-library';
- import {
- IPropertyPaneConfiguration,
- PropertyPaneTextField
- } from '@microsoft/sp-property-pane';
- import { BaseClientSideWebPart } from '@microsoft/sp-webpart-base';
- import * as strings from 'SpfxListViewWebPartStrings';
- import SpfxListView from './components/SpfxListView';
- import { ISpfxListViewProps } from './components/ISpfxListViewProps';
-
- export interface ISpfxListViewWebPartProps {
- description: string;
- }
-
- export default class SpfxListViewWebPart extends BaseClientSideWebPart <ISpfxListViewWebPartProps> {
- public render(): void {
- const element: React.ReactElement<ISpfxListViewProps> = React.createElement(
- SpfxListView,
- {
- description: this.properties.description,
- context:this.context
- }
- );
-
- ReactDom.render(element, this.domElement);
- }
-
- protected onDispose(): void {
- ReactDom.unmountComponentAtNode(this.domElement);
- }
-
- protected get dataVersion(): Version {
- return Version.parse('1.0');
- }
-
- protected getPropertyPaneConfiguration(): IPropertyPaneConfiguration {
- return {
- pages: [
- {
- header: {
- description: strings.PropertyPaneDescription
- },
- groups: [
- {
- groupName: strings.BasicGroupName,
- groupFields: [
- PropertyPaneTextField('description', {
- label: strings.DescriptionFieldLabel
- })
- ]
- }
- ]
- }
- ]
- };
- }
- }
In SpfxListView.tsx
- import * as React from 'react';
- import { ISpfxListViewProps } from './ISpfxListViewProps';
- import { ListView, IViewField, SelectionMode, GroupOrder, IGrouping } from "@pnp/spfx-controls-react/lib/ListView";
- import {SpfxService }from './SpfxService';
- interface IPnpstate {
- ListData:IListitem[];
- }
- export interface IListitem {
- Title: string;
- Region:string;
- }
-
- export default class SpfxListView extends React.Component<ISpfxListViewProps,IPnpstate> {
- private _SPfxService:SpfxService;
- constructor(props: ISpfxListViewProps, state: IPnpstate) {
- super(props);
- this.state = {
- ListData: []
- };
- this._SPfxService =new SpfxService(this.props.context,this.props.context.pageContext);
- }
- private _getSelection(items: any[]) {
- console.log('Selected items:', items);
- }
-
- public componentDidMount(){
- this._SPfxService.getAllrecords("ListView").then((result:IListitem[]) =>{
- this.setState({ ListData: result });
-
- });
- }
- public render(): React.ReactElement<ISpfxListViewProps> {
- return (
- <div >
- <ListView
- items={this.state.ListData}
- showFilter={true}
- filterPlaceHolder="Search..."
- compact={true}
- selectionMode={SelectionMode.multiple}
- selection={this._getSelection}
- groupByFields={groupByFields}
- viewFields={viewFields} />
- </div>
- );
- }
- }
- const groupByFields: IGrouping[] = [
- {
- name: "Region",
- order: GroupOrder.descending
- }
- ];
- export const viewFields : IViewField []= [{
- name: "Title",
- displayName: "MyTitle",
-
- isResizable: true,
- sorting: true,
- minWidth: 0,
- maxWidth: 150
- },{
- name: "Region",
- displayName: "MyRegion",
- linkPropertyName: "c",
- isResizable: true,
- sorting: true,
- minWidth: 0,
- maxWidth: 100
- },];
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 :)