Developing Web Parts Using SharePoint Framework - Part Two

Introduction
 
In this article, you will learn about developing and testing a web part which retrieves list items from a SharePoint list. In my previous article, you have seen about SPFx introduction, prerequisites, and steps for setting up the environment:
Here, let us see how to render the items of a custom list with the help of SPFx and REST API.
 
Web part file
 
The web part file (ListItemsFormWebPart.ts) is already present in the project.
 
As you can see on web part class file, the beginning section shows the components to be imported. The styles, web part properties, and other containers are stored as modules/interfaces in different files. Such components are imported from the corresponding files to the class file before using it.
 
Similarly, some of the components required for developing web parts, need to be imported from the library (@microsoft/sp-client-preview).
 
The interfaces are created. This is very similar to C# programming. The interfaces are contracts that meet the needs of a class. In this example, list item collection and list item interfaces are created.The list item collection will hold the set of list items. The list item will hold the item properties, like Title, Author, etc.
  
Then, the class file is defined. The class inherits the default BaseClientSideWebPart class.
 
The class contains the following,
  • Members To declare the variables
  • Constructor To initialize the data.
  • Render method To define the root/full HTML for a web part.
  • Custom methods For custom data manipulations. Here, the custom logic is inserted to get the data from SharePoint.
  • Web part property method (propertyPaneSettings) - Defines the web part properties. I will explain more about this component in the next articles.
Code
 
The following two files (web part file and style file) need to be modified. 
 
ListItemsFormWebPart.ts File
  1. import {  
  2.   BaseClientSideWebPart,  
  3.   IPropertyPaneSettings,  
  4.   IWebPartContext,  
  5.   PropertyPaneTextField  
  6. } from '@microsoft/sp-client-preview';  
  7.   
  8. import styles from './ListItemsForm.module.scss';  
  9. import * as strings from 'listItemsFormStrings';  
  10. import { IListItemsFormWebPartProps } from './IListItemsFormWebPartProps';  
  11.   
  12. export interface spListItems{  
  13.   value: spListItem[]  
  14. }  
  15. export interface spListItem{  
  16.   Title: string;  
  17.   id: string;  
  18.   Created: string;  
  19.   Author: {  
  20.     Title: string;  
  21.   };  
  22. }  
  23.   
  24.   
  25. export default class ListItemsFormWebPart extends BaseClientSideWebPart<IListItemsFormWebPartProps> {  
  26.   private listName: string = "";  
  27.   public constructor(context: IWebPartContext) {  
  28.     super(context);  
  29.   }  
  30.   
  31.   public render(): void {  
  32.     this.domElement.innerHTML = `  
  33.       <div class="${styles.listItemsForm}">  
  34.         <div class="${styles.container}" id="listContent">  
  35.           <div class="ms-Grid-row ms-bgColor-themeDark ms-fontColor-white ${styles.row}">  
  36.   
  37.           </div>  
  38.         </div>  
  39.       </div>`;  
  40.       this.listName = "TestList";  
  41.       this.LoadListItems();  
  42.   }  
  43.   private LoadListItems(): void{  
  44.   
  45.     let url: string = this.context.pageContext.web.absoluteUrl + "/_api/web/lists/getbytitle('"+this.listName+"')/items?$select=Title,Created,Author/Title&$expand=Author";  
  46.     this.GetListItems(url).then((response)=>{  
  47.       this.RenderListItems(response.value);  
  48.     });  
  49.   }  
  50.   
  51.   private GetListItems(url: string): Promise<spListItems>{  
  52.     return this.context.httpClient.get(url).then((response: Response)=>{  
  53.        return response.json();  
  54.     });  
  55.   }  
  56.   private RenderListItems(listItems: spListItem[]): void{  
  57.     let itemsHtml: string = "";  
  58.     itemsHtml+='<h2>'+this.listName+'</h2>';  
  59.     listItems.forEach((listItem: spListItem)=>{  
  60.       let itemTimeStr: string = listItem.Created;  
  61.       let itemTime: Date = new Date(itemTimeStr);  
  62.       itemsHtml += `  
  63.       <div class="${styles.listItem}">  
  64.         <div class="${styles.listItemTitle}">${listItem.Title}</div>  
  65.         <div class="${styles.listItemProps}">Created on ${itemTime.toDateString()} by ${listItem.Author.Title}</div>  
  66.       </div>`;  
  67.     });  
  68.     this.domElement.querySelector("#listContent").innerHTML =itemsHtml;  
  69.   }  
  70.   protected get propertyPaneSettings(): IPropertyPaneSettings {  
  71.     return {  
  72.       pages: [  
  73.         {  
  74.           header: {  
  75.             description: strings.PropertyPaneDescription  
  76.           },  
  77.           groups: [  
  78.             {  
  79.               groupName: strings.BasicGroupName,  
  80.               groupFields: [  
  81.                 PropertyPaneTextField('description', {  
  82.                   label: strings.DescriptionFieldLabel  
  83.                 })  
  84.               ]  
  85.             }  
  86.           ]  
  87.         }  
  88.       ]  
  89.     };  
  90.   }  
  91. }   
Note
  • The first function is default render method that defines the HTML to be displayed on the web part. The custom method is called from here to display the data from SharePoint list. 
  • Three different methods help us in getting the list items from a SharePoint list. GetListItems retrieves the data from SharePoint. RenderListItems displays the data retrieved.
  • As you can see here, style content is referred using string variables (styles). These variables are generated in ListItemsForm.module.scss.ts file once the style content is written in ListItemsForm.module.scss file. 
ListItemsForm.module.scss File
  1. .listItemsForm {  
  2.   .container {  
  3.     max-width: 700px;  
  4.     margin: 0px auto;  
  5.     box-shadow: 0 2px 4px 0 rgba(0, 0, 0, 0.2), 0 25px 50px 0 rgba(0, 0, 0, 0.1);  
  6.   }  
  7.   
  8.   .row {  
  9.     padding: 20px;  
  10.   }  
  11.   
  12.   .listItem {  
  13.     max-width: 715px;  
  14.     margin: 5px auto 5px auto;  
  15.     box-shadow: 0 0 4px 0 rgba(0, 0, 0, 0.2), 0 25px 50px 0 rgba(0, 0, 0, 0.1);  
  16.   }  
  17.   
  18.   .button {  
  19.     text-decoration: none;  
  20.   }  
  21.   .listItemTitle{  
  22.     font-size: large;  
  23.     color: darkblue;  
  24.   }  
  25.   .listItemProps{  
  26.     font-size: small;  
  27.   }  
  28. }  
Note - The style required for the web part (.ts) file is written here.
 
Testing the web part on the local
 
First, let us test the web part using the workbench file. By running the following command on command prompt, you can preview the web part on the workbench page. Make sure you are running the command from the respective web part project folder.
 
 
 
The above command sets up a local Web Server for testing our functionality. It will open the local workbench file where you can add the web part and check the mock HTML of web part. Note that SharePoint data will not be retrieved and shown here.
 

Testing the web part on SharePoint Workbench Page
 
Next, let us check the functionality on workbench file. The workbench file is available on the layouts folder of any SharePoint online site. (https://siteurl/_layouts/15/workbench.aspx)
  

Add the custom web part using the "Add" symbol available on the page. The following snapshot shows the addition.
The following snapshot shows the web part added to the page. This shows the data from the SharePoint list called "TestList".
 
 
Note - "Gulp Serve" command should be running throughout the process. So, any changes made to the web part file will reflect immediately on the page after refreshing.
 
Summary
 
Thus, you have seen developing and testing the web parts on the SharePoint using SPFx with the help of workbench file.
 
What Next ?

In my next articles, you will see the deployment steps, adding web part to web part pages, and customizing the web part properties.