Customizing SharePoint Framework Web Part Properties - Part Two

Updated: Mar 21, 2019

Introduction 

In this article, you will learn how to add custom properties (check box options) to the SharePoint Framework web part.

In my previous article, I  introduced the custom properties on SharePoint Framework (SPFx).

In my SPFx article series, you can learn about SPFx introduction, prerequisites, steps for setting up the environment, and developing and testing the web parts using the local environments.

In this sample, you will see how to add check box options to the SPFx web part properties pane. The web part will render the items of a list with multiple columns based on the checked items.


The list column names are added as check box fields in the properties pane. The columns that are shown on the web part are Title, Created By, and Created Time. Title is the mandatory value shown, and we will see how to bind the other two values into web part.


Check box is rendered based on PropertyPaneCheckbox class. It contains three attributes. They are,

Text - contains the label for the check box item is Checked - boolean value, used to determine whether the item is selected.isEnabled - boolean value, item can be disabled or enabled.


The required interfaces are defined. The required data is imported from other files or libraries using import option. 


import {    

BaseClientSideWebPart,    

IPropertyPaneSettings,    

IWebPartContext,    

PropertyPaneTextField,    

PropertyPaneCheckbox  

from '@microsoft/sp-client-preview';  

import styles from './ListItemsForm.module.scss'; 

import * as strings from 'listItemsFormStrings';  

import { IListItemsFormWebPartProps } from './IListItemsFormWebPartProps';  

export interface spListItems{    

value: spListItem[] 

 }  

export interface spListItem{    

Title: string;   

 id: string;    

Created: string;    

Author: {      

Title: string;   

 };  

}  


To the existing properties page, another group is added. The group contains two check box fields.

  • Created Time

  • Author

Likewise, any number of checkboxes can be added.

The property text variables are initialized in the class before the constructor.


private checkboxProperty1: string = "Created";  

private checkboxProperty2: string = "Author";  


The properties are defined in the propertyPaneSettings method. Users can select or deselect the properties (options). The following snippet shows the method.


protected get propertyPaneSettings(): IPropertyPaneSettings {  

return {      

pages: [        {          

header: {            

description: strings.PropertyPaneDescription          

},          

groups: [            {              

groupName: strings.BasicGroupName,              

groupFields: [                

PropertyPaneTextField('description', {                  

label: strings.DescriptionFieldLabel                

})              ]            },            {              

groupName: "OptionalFields",              

groupFields: [                

PropertyPaneCheckbox('checkboxProperty1',

{                  

isChecked:false,                  

isEnabled:true,                 

 text: this.checkboxProperty1                

}),                

PropertyPaneCheckbox('checkboxProperty2',

{                  

isChecked:false,                  

isEnabled:true,                  

text: this.checkboxProperty2                

})              ]            }          ]        }      ]    };  }  


Based on the check box options selected, REST API is constructed, and the items are retrieved from the list. The list items are then displayed in tabular format. Render method displays the data on the web part. The custom methods render the list items based on the properties selected. Appropriate style content is referred from the .scss file.


public render(): void 

{  

// Render the items in tabular format

this.domElement.innerHTML = `      

<div class="${styles.listItemsForm}">        

<div class="${styles.Table}">          

<div class="${styles.Heading}">            

<div class="${styles.Cell}">Title</div>         

 </div>        </div>      </div>`;  

this.listName = "TestList";  

this.LoadData();  

}  

private LoadData(): void{     

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

// If Created Time check box option is selected

if(this.properties.checkboxProperty1)

{      

url += ",Created";  

// Column header for Created Time field this.domElement.querySelector("."+styles.Heading).innerHTML +=`<div class="${styles.Cell}">Created</div>`;    

}  

// If Author check box option is selected

if(this.properties.checkboxProperty2)

{      

url += ",Author/Title&$expand=Author";  

// Column header for Author field this.domElement.querySelector("."+styles.Heading).innerHTML +=`<div class="${styles.Cell}">Author</div>`;    

}  

this.GetListData(url).then((response)=>{  

// Render the data in the web part

this.RenderListData(response.value);    

});  

}  

private GetListData(url: string): Promise<spListItems>{  

// Retrieves data from SP list

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

});  

}  

private RenderListData(listItems: spListItem[]): void{    

let itemsHtml: string = "";  

// Displays the values in table rows   

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

let itemTimeStr: string = listItem.Created;      

let itemTime: Date = new Date(itemTimeStr);      

itemsHtml += `<div class="${styles.Row}">`;      

itemsHtml += `<div class="${styles.Cell}"><p>${listItem.Title}</p></div>`;   if(this.properties.checkboxProperty1){        

itemsHtml += `<div class="${styles.Cell}"><p>${listItem.Created}</p></div>`;      

}  

if(this.properties.checkboxProperty2){        

itemsHtml += `<div class="${styles.Cell}"><p>${listItem.Author.Title}</p></div>`;      

}       

itemsHtml += `</div>`;    

});  

this.domElement.querySelector("."+styles.Table).innerHTML +=itemsHtml;  

}  


For example, this.properties.checkboxProperty1 gives the boolean value for the first check box option ("Created Time" column). The following snapshot shows the list items displayed based on the check box.



The below snapshot shows the list items without "Created Time" column.


Note The web part can be deployed to the site and added to the page. In my previous article, you can see the steps for deployment. 


Entire Code

The changes made to the different files are shown in the following code snippets.


IListItemsFormWebPartProps.ts File

export interface IListItemsFormWebPartProps 

{    

description: string;    

checkboxProperty1: string;    

checkboxProperty2: string;  

}  

ListItemsForm.module.scss File

.listItemsForm {    

.container {      

max-width: 700px;      

margin: 0px auto;      

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

}     

.row {      

padding: 20px;    

}     

.listItem {      

max-width: 715px;     

 margin: 5px auto 5px auto;      

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

}    

 .button {      

text-decoration: none;    

}    

.listItemTitle{      

font-size: large;      

color: darkblue;    

}    

.listItemProps{      

font-size: small;    

}     

.Table      

{          

display: table;      

}     

 .Title      

{          

display: table-caption;          

text-align: center;          

font-weight: bold;          

font-size: larger;      

}      

.Heading      

{          

display: table-row;          

font-weight: bold;          

text-align: center;      

}      

.Row      

{          

display: table-row;      

}     

 .Cell      

{          

display: table-cell;          

border: solid;          

border-width: thin;          

padding-left: 5px;          

padding-right: 5px;      

}  }  

ListItemsFormWebPart.ts File

import 

{    

BaseClientSideWebPart,    

IPropertyPaneSettings,    

IWebPartContext,    

PropertyPaneTextField,    

PropertyPaneCheckbox  

from '@microsoft/sp-client-preview';  

import styles from './ListItemsForm.module.scss';  

import * as strings from 'listItemsFormStrings';  

import { IListItemsFormWebPartProps } from './IListItemsFormWebPartProps';  

export interface spListItems{    value: spListItem[]  }  

export interface spListItem{    Title: string;    id: string;    Created: string;    Author: {      Title: string;    };  }   export default class ListItemsFormWebPart 

extends BaseClientSideWebPart<IListItemsFormWebPartProps> {  

private listName: string = "";  

private checkboxProperty1: string = "Created";  

private checkboxProperty2: string = "Author";  

public constructor(context: IWebPartContext) 

{  

super(context);    

}  

public render(): void {   // Render the items in tabular format this.domElement.innerHTML = `        

<div class="${styles.listItemsForm}">          

<div class="${styles.Table}">            

<div class="${styles.Heading}">              

<div class="${styles.Cell}">Title</div>            

</div>          </div>        </div>`;  

this.listName = "TestList";   this.LoadData();    

}  

private LoadData(): void{       

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

// If Created Time check box option is selected

if(this.properties.checkboxProperty1)

{        

url += ",Created";  

// Column header for Created Time field this.domElement.querySelector("."+styles.Heading).innerHTML +=`<div class="${styles.Cell}">Created</div>`;      

}  

// If Author check box option is selected

if(this.properties.checkboxProperty2){        

url += ",Author/Title&$expand=Author";  

// Column header for Author field this.domElement.querySelector("."+styles.Heading).innerHTML +=`<div class="${styles.Cell}">Author</div>`;      

}  

this.GetListData(url).then((response)=>{  

// Render the data in the web part this.RenderListData(response.value);      

});    }  

private GetListData(url: string): Promise<spListItems>{   /

/ Retrieves data from SP list

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

{  

return response.json();      

});    

}  

private RenderListData(listItems: spListItem[]): void{      

let itemsHtml: string = "";  

// Displays the values in table rows     

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

let itemTimeStr: string = listItem.Created;        

let itemTime: Date = new Date(itemTimeStr);       

 itemsHtml += `<div class="${styles.Row}">`;       

 itemsHtml += `<div class="${styles.Cell}"><p>${listItem.Title}</p></div>`;   if(this.properties.checkboxProperty1)

{         

 itemsHtml += `<div class="${styles.Cell}"><p>${listItem.Created}</p></div>`;        

}  

if(this.properties.checkboxProperty2){         

 itemsHtml += `<div class="${styles.Cell}"><p>${listItem.Author.Title}</p></div>`;        

}         

itemsHtml += `</div>`;     

 });  

this.domElement.querySelector("."+styles.Table).innerHTML +=itemsHtml;    

}  

protected get propertyPaneSettings(): IPropertyPaneSettings 

{  

return {        

pages: [          {            

header: {              

description: strings.PropertyPaneDescription            

},            

groups: [              {                

groupName: strings.BasicGroupName,                

groupFields: [                  

PropertyPaneTextField('description', {                    

label: strings.DescriptionFieldLabel                  

})                ]              

},              

{                

groupName: "OptionalFields",                

groupFields: [                  

PropertyPaneCheckbox('checkboxProperty1',

{                    

isChecked:false,                    

isEnabled:true,                    

text: this.checkboxProperty1                  

}),                  

PropertyPaneCheckbox('checkboxProperty2',{                    

isChecked:false,                    

isEnabled:true,                    

text: this.checkboxProperty2                  

})                ]             

 }            ]          

}        ]      

};    

}  }  


Summary

Thus, you have learned how to add the check box fields to the SharePoint Framework web part properties.


What Next

In the next articles, you will learn about working with multiple pages on the property pane and adding other custom properties that are available. 

Recent Posts

See All