Developing Web Parts Using SharePoint Framework - Part Two

Updated: Apr 30, 2019


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.


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  } from '@microsoft/sp-client-preview';   import styles from './ListItemsForm.module.scss';  

  6. import * as strings from 'listItemsFormStrings';  

  7. import { IListItemsFormWebPartProps } from './IListItemsFormWebPartProps';  

  8. export interface spListItems{    

  9. value: spListItem[]  

  10. }  

  11. export interface spListItem{    

  12. Title: string;    

  13. id: string;    

  14. Created: string;    

  15. Author: {      

  16. Title: string;    

  17. };  

  18. }  

  19. export default class ListItemsFormWebPart extends BaseClientSideWebPart<IListItemsFormWebPartProps> 

  20. {  

  21. private listName: string = "";  

  22. public constructor(context: IWebPartContext) {      

  23. super(context);    

  24. }  

  25. public render(): void {  

  26. this.domElement.innerHTML = `<div class="${styles.listItemsForm}">          

  27. <div class="${styles.container}" id="listContent">            

  28. <div class="ms-Grid-row ms-bgColor-themeDark ms-fontColor-white ${styles.row}">             

  29. </div>          

  30. </div>        

  31. </div>`;  

  32. this.listName = "TestList";  

  33. this.LoadListItems();    }  

  34. private LoadListItems(): void{       

  35. let url: string = this.context.pageContext.web.absoluteUrl + "/_api/web/lists/getbytitle('"+this.listName+"')/items?

  36. $select=Title,Created,Author/Title&$expand=Author";  

  37. this.GetListItems(url).then((response)=>{  

  38. this.RenderListItems(response.value);      

  39. });    

  40. }  

  41. private GetListItems(url: string): Promise<spListItems>{  

  42. return this.context.httpClient.get(url).then((response: Response)=>{  

  43. return response.json();      

  44. });    

  45. }  

  46. private RenderListItems(listItems: spListItem[]): void{      

  47. let itemsHtml: string = "";      

  48. itemsHtml+='<h2>'+this.listName+'</h2>';      

  49. listItems.forEach((listItem: spListItem)=>

  50. {        

  51. let itemTimeStr: string = listItem.Created;        

  52. let itemTime: Date = new Date(itemTimeStr);        

  53. itemsHtml += `<div class="${styles.listItem}">          

  54. <div class="${styles.listItemTitle}">${listItem.Title}

  55. </div>          

  56. <div class="${styles.listItemProps}">Created on ${itemTime.toDateString()} by ${listItem.Author.Title}</div>        

  57. </div>`;      

  58. });  

  59. this.domElement.querySelector("#listContent").innerHTML =itemsHtml;    

  60. }  

  61. protected get propertyPaneSettings(): IPropertyPaneSettings {  

  62. return {        

  63. pages: [          {            

  64. header: {              

  65. description: strings.PropertyPaneDescription            

  66. },            

  67. groups: [              {                

  68. groupName: strings.BasicGroupName,                

  69. groupFields: 

  70. [                  

  71. PropertyPaneTextField('description', {                    

  72. label: strings.DescriptionFieldLabel                  

  73. })               

  74.  ]              

  75. }           

  76.  ]          

  77. }        

  78. ]      

  79. };    

  80. }  

  81. }  


  • 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. .row {      

  7. padding: 20px;    

  8. }     

  9. .listItem {      

  10. max-width: 715px;      

  11. margin: 5px auto 5px auto;      

  12. box-shadow: 0 0 4px 0 rgba(0, 0, 0, 0.2), 0 25px 50px 0 rgba(0, 0, 0, 0.1);    }    

  13.  .button {      

  14. text-decoration: none;    

  15. }    

  16. .listItemTitle{      

  17. font-size: large;      

  18. color: darkblue;    

  19. }    

  20. .listItemProps{      

  21. font-size: small;    

  22. }  

  23. }  

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.


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.

Recent Posts

See All

How To Use CSRF Tokens With Laravel

Very often with a Laravel application you will have some type of CRUD (Create, Read, Update, Delete). This, of course requires HTML forms and submitting data from the front-end to the back end control