Create A Webpart Which Will Retrieve List And Document Using SPFx

Introduction 

 
In this blog, we are going to discuss the creation of a new webpart using SPFx (no JavaScript framework). This webpart will represent the data of the corresponding site such as website name, website URL, Total List Count. It retrieves the name of all custom lists and documents.
 
Let's get started …
 
Step A - (Creation of the Webpart)
 
Open the Command Prompt. Go to the drive where which you want to create the Project. Here I have created the project in “c-drive”.
 
Run the below commands:
 
“cd C:\”
“md Webpart”
 
Refer to image-1 for more details.
 
Create A Webpart Which will retrieve the List and Document using SPFx 
 
Refer to image-2 and run the command “yo @microsoft/sharepoint”. Then enter the requested details the same as mentioned in Image-2 to create the webpart. The webpart creation may take some time, so wait to complete the installation.
 
After completion, you will see a congratulation message (Check Image-3).
 
Create A Webpart Which will retrieve the List and Document using SPFx 
 
Create A Webpart Which will retrieve the List and Document using SPFx 
 
Then run the command code .to open the Visual studio code.
 
Expand src-> webparts (Refer image-4) to open the files.
 
Create A Webpart Which will retrieve the List and Document using SPFx 
 
Step B - (Create a New File)
 
Create a new file inside C: \WebPart\src\webparts\dynamicWp. Name it as “GetList.ts” as shown in image:5.
 
Create A Webpart Which will retrieve the List and Document using SPFx
 
Create A Webpart Which will retrieve the List and Document using SPFx 
 
Step C - (Change the code)
 
Here I have mentioned the code for corresponding files. So please refer to the instructions accordingly and add/change the code.
 
In “DynamicWPWebPart.ts” replace the below code.
  1. import pnp from "sp-pnp-js";  
  2. import {  
  3.     Version  
  4. } from '@microsoft/sp-core-library';  
  5. import {  
  6.     IPropertyPaneConfiguration,  
  7.     PropertyPaneTextField,  
  8.     PropertyPaneDropdown  
  9. } from '@microsoft/sp-property-pane';  
  10. import {  
  11.     BaseClientSideWebPart  
  12. } from '@microsoft/sp-webpart-base';  
  13. import {  
  14.     escape  
  15. } from '@microsoft/sp-lodash-subset';  
  16. import styles from './DynamicWpWebPart.module.scss';  
  17. import * as strings from 'DynamicWpWebPartStrings';  
  18. import MockHttpClient from './GetList';  
  19. import {  
  20.     SPHttpClient,  
  21.     SPHttpClientResponse  
  22. } from '@microsoft/sp-http';  
  23. import {  
  24.     Environment,  
  25.     EnvironmentType  
  26. } from '@microsoft/sp-core-library';  
  27. import "@pnp/sp/webs";  
  28. import "@pnp/sp/lists";  
  29. import {  
  30.     _List  
  31. } from '@pnp/sp/lists/types';  
  32. export interface IDynamicWpWebPartProps {  
  33.     description: string;  
  34.     List: string;  
  35. }  
  36. export interface ISPLists {  
  37.     value: ISPList[];  
  38. }  
  39. export interface ISPList {  
  40.     Title: string;  
  41.     Id: string;  
  42.     BaseTemplate: string;  
  43. }  
  44. let array: string[];  
  45. export default class DynamicWpWebPart extends BaseClientSideWebPart < IDynamicWpWebPartProps > {  
  46.     private _renderList(): void {  
  47.         if (Environment.type === EnvironmentType.Local) {  
  48.             this._getItemsFromList().then((response) => {  
  49.                 this._listDesign(response.value);  
  50.             });  
  51.         } else if (Environment.type == EnvironmentType.SharePoint || Environment.type == EnvironmentType.ClassicSharePoint) {  
  52.             this._getListData().then((response) => {  
  53.                 this._listDesign(response.value);  
  54.             });  
  55.         }  
  56.     }  
  57.     private _listDesign(items: ISPList[]): void {  
  58.         let html: string = '';  
  59.         let i = 0;  
  60.         html += `  
  61.     <div>  
  62.         <p class="${ styles.label} style="margin:5px;5px;5px;5px; font-weight: bold">Total List Count : ${items.length}</p>  
  63.     </div>`;  
  64.   
  65.     html +=`  
  66.     <div>  
  67.         <b style="font-size:20px;">Document</b>`  
  68.     items.forEach((item: ISPList) => {  
  69.       if (item.BaseTemplate=='101') {  
  70.         html += `  
  71.         <ul class="${styles.list}">  
  72.             <li class="${styles.listItem}">  
  73.                 <span class="ms-font-l">Document Title :   
  74.                     <b>${item.Title}</b>  
  75.                 </span>  
  76.             </li>  
  77.         </ul>`;  
  78.   
  79.       }  
  80.     });  
  81.         html += ` </div>`;  
  82.         html += `<div><b style="font-size:20px;">List</b>`  
  83.         items.forEach((item1: ISPList) => {  
  84.             if (item1.BaseTemplate == '100') {  
  85.                 html += `  
  86.         <ul class="${styles.list}">  
  87.             <li class="${styles.listItem}">  
  88.                 <span class="ms-font">List Title :   
  89.                     <b>${item1.Title}</b>  
  90.                 </span>  
  91.             </li>  
  92.         </ul>`  
  93.   
  94.       }  
  95.   
  96.     });  
  97.         html += ` </div>`;  
  98.         const listContainer: Element = this.domElement.querySelector('#spListContainer');  
  99.         listContainer.innerHTML = html;  
  100.     }  
  101.     private _getListData(): Promise < ISPLists > {  
  102.         return this.context.spHttpClient.get(this.context.pageContext.web.absoluteUrl + `/_api/web/lists?$filter=Hidden eq false`, SPHttpClient.configurations.v1).then((response: SPHttpClientResponse) => {  
  103.             return response.json();  
  104.         });  
  105.     }  
  106.     private _getItemsFromList(): Promise < ISPLists > {  
  107.         return MockHttpClient.get().then((data: ISPList[]) => {  
  108.             var listData: ISPLists = {  
  109.                 value: data  
  110.             };  
  111.             return listData;  
  112.         }) as Promise < ISPLists > ;  
  113.     }  
  114.   public render(): void {  
  115.   
  116.     this.domElement.innerHTML = `  
  117.                 <textarea placeholder="DynamicWP" aria-label="Add a title" style="height: 23px; border:none;font-size:20px;font-weight: bold; width: 100%;"></textarea>  
  118.                 <div class="${ styles.dynamicWp }">  
  119.                     <div class="${ styles.container }">  
  120.                         <div class="${ styles.row }">  
  121.                             <div class="${ styles.column }">  
  122.                                 <div>  
  123.                                     <p class="${ styles.label} style="margin:5px;5px;5px;5px; font-weight: bold">WebSite Name : ${escape(this.context.pageContext.web.title)}</p>  
  124.                                 </div>  
  125.                                 <div>  
  126.                                     <p class="${ styles.label} style="margin:5px;5px;5px;5px; font-weight: bold">WebSite URL : ${escape(this.context.pageContext.site.absoluteUrl)}</p>  
  127.                                 </div>  
  128.                                 <div id="spListContainer"/>  
  129.                                 <p class="${ styles.description }">${escape(this.properties.description)}</p>  
  130.                             </div>  
  131.                         </div>  
  132.                     </div>  
  133.                 </div>`;  
  134.   
  135.       this._renderList();  
  136.   
  137.   }  
  138.     protected get dataVersion(): Version {  
  139.         return Version.parse('1.0');  
  140.     }  
  141.     protected getPropertyPaneConfiguration(): IPropertyPaneConfiguration {  
  142.         return {  
  143.             pages: [{  
  144.                 header: {  
  145.                     description: strings.PropertyPaneDescription,  
  146.                     list: strings.List  
  147.                 },  
  148.                 groups: [{  
  149.                     groupName: strings.BasicGroupName,  
  150.                     groupFields: [  
  151.                         PropertyPaneTextField('Description', {  
  152.                             label: strings.DescriptionFieldLabel  
  153.                         })  
  154.                     ]  
  155.                 }]  
  156.             }]  
  157.         };  
  158.     }  
  159. }  
In “GetList.ts” add the below code.
  1. import {  
  2.     ISPList  
  3. } from './DynamicWpWebPart';  
  4. export default class GetDemoList {  
  5.     private static_items: ISPList[] = [{  
  6.         Title: 'List 1',  
  7.         BaseTemplate: '101',  
  8.         Id: '1'  
  9.     }, {  
  10.         Title: 'List 2',  
  11.         BaseTemplate: '101',  
  12.         Id: '2'  
  13.     }, {  
  14.         Title: 'List 3',  
  15.         BaseTemplate: '101',  
  16.         Id: '3',  
  17.     }];  
  18.     public static get(): Promise < ISPList[] > {  
  19.         return new Promise < ISPList[] > ((resolve) => {  
  20.             resolve(GetDemoList._items);  
  21.         });  
  22.     }  
  23. }  
In “mystrings.d.ts” replace the below code.
  1. declareinterfaceIDynamicWpWebPartStrings {  
  2.     PropertyPaneDescription: string;  
  3.     BasicGroupName: string;  
  4.     DescriptionFieldLabel: string;  
  5.     List: string;  
  6. }  
  7. declaremodule 'DynamicWpWebPartStrings' {  
  8.     conststrings: IDynamicWpWebPartStrings;  
  9.     export = strings;  
  10. }  
In “en-us.js” replace the below code.
  1. define([], function() {  
  2.     return {  
  3.         "PropertyPaneDescription""Description",  
  4.         "BasicGroupName""Group Name",  
  5.         "DescriptionFieldLabel""Description Field",  
  6.         "ListFieldLable""Lists"  
  7.     }  
  8. });  
InDynamicWpWebPart.module.scssreplace the below code.
  1. @import '~@microsoft/sp-office-ui-fabric-core/dist/sass/SPFabricCore.scss';.dynamicWp {  
  2.     .container {  
  3.         max - width: 700 px;  
  4.         margin: 0 pxauto;  
  5.         box - shadow: 02 px4px0rgba(0, 0, 0, 0.2), 025 px50px0rgba(0, 0, 0, 0.1);  
  6.     }.row {  
  7.         @includems - Grid - row;  
  8.         @includems - fontColor - white;  
  9.         background - color: $ms - color - themeDark;  
  10.         padding: 20 px;  
  11.     }.column {  
  12.         @includems - Grid - col;  
  13.         @includems - lg10;  
  14.         @includems - xl8;  
  15.         @includems - xlPush2;  
  16.         @includems - lgPush1;  
  17.     }.title {  
  18.         @includems - font - xl;  
  19.         @includems - fontColor - white;  
  20.     }.subTitle {  
  21.         @includems - font - l;  
  22.         @includems - fontColor - white;  
  23.     }.description {  
  24.         @includems - font - l;  
  25.         @includems - fontColor - white;  
  26.     }.button {  
  27.         // Our button  
  28.         text - decoration: none;  
  29.         height: 32 px;  
  30.         // Primary Button  
  31.         min - width: 80 px;  
  32.         background - color: $ms - color - themePrimary;  
  33.         border - color: $ms - color - themePrimary;  
  34.         color: $ms - color - white;  
  35.         // Basic Button  
  36.         outline: transparent;  
  37.         position: relative;  
  38.         font - family: "Segoe UI WestEuropean""Segoe UI", -apple - system, BlinkMacSystemFont, Roboto, "Helvetica Neue", sans - serif; - webkit - font - smoothing: antialiased;  
  39.         font - size: $ms - font - size - m;  
  40.         font - weight: $ms - font - weight - regular;  
  41.         border - width: 0;  
  42.         text - align: center;  
  43.         cursor: pointer;  
  44.         display: inline - block;  
  45.         padding: 016 px;.label {  
  46.             font - weight: $ms - font - weight - semibold;  
  47.             font - size: $ms - font - size - m;  
  48.             height: 32 px;  
  49.             line - height: 32 px;  
  50.             margin: 04 px;  
  51.             vertical - align: top;  
  52.             display: inline - block;  
  53.         }  
  54.     }.list {  
  55.         color: #333333;  
  56. font-family: 'Segoe UI Regular WestEuropean''Segoe UI', Tahoma, Arial, sans-serif;  
  57. font-size: 14px;  
  58. font-weight: normal;  
  59. box-sizing: border-box;  
  60. background-color: # ffffff;  
  61.         margin: 10;  
  62.         padding: 10;  
  63.         line - height: 50 px;  
  64.         list - style - type: none;  
  65.         box - shadow: 04 px4px0rgba(0, 0, 0, 0.2),  
  66.         025 px50px0rgba(0, 0, 0, 0.1);  
  67.     }.listItem {  
  68.         color: #333333;  
  69. vertical-align: center;  
  70. font-family: 'Segoe UI Regular WestEuropean''Segoe UI', Tahoma, Arial, sans-serif;  
  71. font-size: 14px;  
  72. font-weight: normal;  
  73. box-sizing: border-box;  
  74. margin: 0;  
  75. padding: 0;  
  76. background-color: # ffffff;  
  77.         box - shadow: none;* zoom: 1;  
  78.         padding: 9 px28px3px;  
  79.         position: relative;  
  80.     }  
  81. }  
Step D - (Add the webpart)
 
After following the above steps save all the files. In the command prompt run the command “gulp serve”. The browser will open automatically and by clicking on the plus sign you can add the webpart DynamicWP. (Refer to image-7).
 
Create A Webpart Which will retrieve the List and Document using SPFx 
 
The final webpart will appear as below image. (Refer to image-8).
 
Create A Webpart Which will retrieve the List and Document using SPFx