SharePoint Framework: Create Client Web Part to Retrieve and Display List Items
In this section, we will be creating a client Web part using TypeScript, which will be retrieving the list items from SharePoint List (EmployeeList) and display it in the tabular form in the client Web part, as shown below.
The Solutions files used in this section is zipped and uploaded to the Microsoft TechNet gallery. Feel free to download it.
Create the Web part Project
Spin up Node.js command prompt, using which we will be creating the Web part project structure.
This will open the console where we can create the SharePoint Framework project structure.We can create the directory, where we will be adding the solution, using the command given below.
md GetSharePointListItems
Let’s move to the newly created working directory, using the command.
cd GetSharePointListItems
We will then create the client Web part by running the Yeoman SharePoint Generator.
yo @microsoft/sharepoint
This will display the prompt, which we must fill up, to proceed with the project creation.
What is your solution name? : Set it to ‘GetSPListItems’.
On pressing enter, we will be asked to chose the working folder for the project.
Where do you want to place your files- Use current folder.
What framework would you like to start with- Select “No javaScript web framework” for the time being, as this is a sample Web part.
What is your Webpart name- We will specify it as ‘GetSPListItems’ and press Enter
What is your Webpart description- We will specify it as this Webpart will retrieve the list items from SharePoint list and display in a table
Yeoman has started working on the scaffolding of the project. It will install the required dependencies and scaffold the solution files for the ‘GetListItems’ Web part, which will take some time to complete. Once completed, we will get a congratulations message.
Test the Web part locally
To test the client Web part, we can build and run it on the local Web Server, where we are developing the Web part. SharePoint Framework development uses HTTPS endpoint by default. Since a default certificate is not configured for the local development environment, our Browser will report a
certificate error. SharePoint Framework tool chain comes with a developer certificate, which we can install for testing the client Web parts locally. From the current Web part directory, run the command given below.
gulp trust-dev-cert
Now, let’s preview the Web part by running the
gulp serve
command.
This command will execute a series of gulp tasks and will create a Node-based HTTPS Server at 'localhost:4321'. It will then open the Browser and display the client Web part.This indicates that the project structure is set up correctly. We will now open the solution in Visual Studio Code to add the logic to retrieve the list items from SharePoint and display it as a table in this page.
To stop Gulp from listening to the process, we can press ‘
Control + C’
. This will terminate the Gulp Serve command and stop the Server.
Edit the web part
Now let’s try to edit the web part and add more functionality to it. To do that navigate to “src\webparts\getSpListItems” location.
In the left pane of Visual Studio Code, we can see the project structure. The bulk of the logic resides within the
GetSPListItemsWebPart.ts
file. Let’s add the code to retrieve SharePoint list items from the Employee List within this TypeScript file.
Define List Model
Since we want to retrieve an Employee list items data, we will be creating list model with SharePoint list fields in the GetSpListItemsWebPart.TS file, as shown below. Place it above the ‘GetSpListItemsWebPart’ class.
export interface ISPLists
{
value: ISPList[];
}
export interface ISPList {
EmployeeId: string;
EmployeeName: string;
Experience: string;
Location: string;
}
Create Mock HTTPClient to test data locally
To test the list item retrieval in the local workbench, we will create a mock store, which returns mock Employee list data. We will create a new file inside ‘src\webparts\ getSpListItems’ folder named MockHttpClient.ts, as shown below.
We will then copy the code given below into MockHttpClient.ts, as shown below.
import { ISPList } from './GetSpListItemsWebPart'; 2.
export default class MockHttpClient {
private static _items: ISPList[] = [{ EmployeeId: 'E123', EmployeeName: 'John', Experience: 'SharePoint',Location:'India' },];
public static get(restUrl: string, options?: any): Promise<ISPList[]> {
return new Promise<ISPList[]>((resolve) => {
resolve(MockHttpClient._items); 8. });
}
}
We can now use the MockHttpClient class in the ‘GetSPListItems’ class.
Let’s import the ‘MockHttpClient’ module by going to the GetSpLitItemsWebPart.ts and pasting the line given below just after “
import { IGetSpListItemsWebPartProps } from './IGetSpListItemsWebPartProps';”
import MockHttpClient from './MockHttpClient';
We will also add the mock list item retrieval method within the ‘GetSpListItemsWebPart’ class.
private _getMockListData(): Promise<ISPLists> {
return MockHttpClient.get(this.context.pageContext.web.absoluteUrl).then(() => {
const listData: ISPLists = {
value:
[. { EmployeeId: 'E123', EmployeeName: 'John', Experience: 'SharePoint',Location: 'India' },
{ EmployeeId: 'E567', EmployeeName: 'Martin', Experience: '.NET',Location: 'Qatar' },
{ EmployeeId: 'E367', EmployeeName: 'Luke', Experience: 'JAVA',Location: 'UK' }
]
};
return listData;
}) as Promise<ISPLists>;
}
Retrieve SharePoint List Items
SharePoint Framework has the helper class spHttpClient, which can be utilized to call REST API requests against SharePoint.
We will use REST API:
“/_api/web/lists/GetByTitle('EmployeeList')/Items"
to get the list items from SharePoint List.
To use ‘spHttpClient’, we will first have to import it from the ‘@microsoft/sp-http’ module. We will import this module by placing the line given below after the mockHttpClient import code -
“import MockHttpClient from './MockHttpClient';
”
import { SPHttpClient
} from '@microsoft/sp-http';
We will be then adding the method given below to get SharePoint list items, using REST API within the ‘GetSpListItemsWebPart’ class.
private _getListData(): Promise<ISPLists> {
return this.context.spHttpClient.get(this.context.pageContext.web.absoluteUrl +
`/_api/web/lists/GetByTitle('EmployeeList')/Items`, SPHttpClient.configurations.v1)
.then((response: Response) => {
debugger;
return response.json();
});
}
Render the SharePoint List Items from Employee List
Once we run the gulp serve command, we can test the Web part in SharePoint Workbench in the local environment or using SharePoint Online Context. SharePoint Framework uses ‘EnvironmentType’ module to identify the environment, where the Web part is executed.
In order to implement this, we will import ‘Environment’ and the ‘EnvironmentType’ modules from the @microsoft/sp-core-library bundle by placing it at the top of the GetSpListItemsWebpart.ts file.
import { Environment, EnvironmentType
} from '@microsoft/sp-core-library';
We will then check Environment.type value and if it is equal to Environment.Local, the MockHttpClient method, which returns dummy data which will be called else the method that calls REST API which can retrieve SharePoint list items will be called.
private _renderListAsync(): void {
if (Environment.type === EnvironmentType.Local) {
this._getMockListData().then((response) => {
this._renderList(response.value);
});
}
else {
this._getListData()
.then((response) => {
this._renderList(response.value);
});
}
}
Finally, we will add the method given below, which will create HTML table out of the retrieved SharePoint list items.
private _renderList(items: ISPList[]): void {
let html: string = '<table class="TFtable" border=1 width=100% style="border- collapse: collapse;">';
html +=
`<th>EmployeeId</th><th>EmployeeName</th><th>Experience</th><th>Location</th>`;
items.forEach((item: ISPList) => {
html += `
<tr>
<td>${item.EmployeeId}</td>
<td>${item.EmployeeName}</td>
<td>${item.Experience}</td>
<td>${item.Location}</td>
</tr>
`;
});
html += `</table>`;
const listContainer: Element = this.domElement.querySelector('#spListContainer');
listContainer.innerHTML = html;
}
To enable rendering of the list items given above, we will replace Render method in the ‘GetSpListItemsWebPart’ class with the code given below.
public render(): void {
this.domElement.innerHTML = `
<div class="${styles.helloWorld}">
<div class="${styles.container}">
<div class="ms-Grid-row ms-bgColor-themeDark ms-fontColor-white ${styles.row}">
<div class="ms-Grid-col ms-u-lg10 ms-u-xl8 ms-u-xlPush2 ms-u-lgPush1">
<span class="ms-font-xl ms-fontColor-white" style="font-size:28px">Welcome to SharePoint Framework Development</span>
<p class="ms-font-l ms-fontColor-white" style="text-align: center">Demo : Retrieve Employee Data from SharePoint List</p>
</div>
</div>
<div class="ms-Grid-row ms-bgColor-themeDark ms-fontColor-white ${styles.row}">
<div style="background-color:Black;color:white;text-align: center;font-weight: bold;font-size:18px;">Employee Details</div>
<br>
<div id="spListContainer" />
</div>
</div> 18. </div>`;
this._renderListAsync();
}
TS File Contents
The code contents used in the TS file to retrieve and display list items are given below:
import { Version } from '@microsoft/sp-core-library';
import {
BaseClientSideWebPart,
IPropertyPaneConfiguration,
PropertyPaneTextField
} from '@microsoft/sp-webpart-base';
import { escape } from '@microsoft/sp-lodash-subset'; 8.
import {
Environment,
EnvironmentType
} from '@microsoft/sp-core-library'; 13.
import styles from './GetSpListItems.module.scss';
import * as strings from 'getSpListItemsStrings';
import { IGetSpListItemsWebPartProps } from './IGetSpListItemsWebPartProps';
import MockHttpClient from './MockHttpClient';
import {
SPHttpClient
} from '@microsoft/sp-http';
export interface ISPLists {
value: ISPList[];
}
export interface ISPList {
EmployeeId: string;
EmployeeName: string;
Experience: string;
Location: string;
}
export default class GetSpListItemsWebPart extends BaseClientSideWebPart<IGetSpListItemsWebPartProps> {
private _getListData(): Promise<ISPLists> {
return this.context.spHttpClient.get(this.context.pageContext.web.absoluteUrl +
`/_api/web/lists/GetByTitle('EmployeeList')/Items`, SPHttpClient.configurations.v1)
.then((response: Response) => {
debugger;
return response.json();
});
}
private _renderListAsync(): void {
if (Environment.type === EnvironmentType.Local) {
this._getMockListData().then((response) => {
this._renderList(response.value);
});
}
else {
this._getListData()
.then((response) => {
this._renderList(response.value); });
}
}
private _renderList(items: ISPList[]): void {
let html: string = '<table class="TFtable" border=1 width=100% style="border- collapse: collapse;">';
html +=
`<th>EmployeeId</th><th>EmployeeName</th><th>Experience</th><th>Location</th>`;
items.forEach((item: ISPList) => {
html += `
<tr>
<td>${item.EmployeeId}</td>
<td>${item.EmployeeName}</td>
<td>${item.Experience}</td>
<td>${item.Location}</td>
</tr>
`;
});
html += `</table>`;
const listContainer: Element = this.domElement.querySelector('#spListContainer');
listContainer.innerHTML = html;
}
public render(): void {
this.domElement.innerHTML = `
<div class="${styles.helloWorld}">
<div class="${styles.container}">
<div class="ms-Grid-row ms-bgColor-themeDark ms-fontColor-white ${styles.row}">
<div class="ms-Grid-col ms-u-lg10 ms-u-xl8 ms-u-xlPush2 ms-u-lgPush1">
<span class="ms-font-xl ms-fontColor-white" style="font-size:28px">Welcome to SharePoint Framework Development</span>
<p class="ms-font-l ms-fontColor-white" style="text-align: center">Demo : Retrieve Employee Data from SharePoint List</p>
</div>
</div>
<div class="ms-Grid-row ms-bgColor-themeDark ms-fontColor-white ${styles.row}">
<div style="background-color:Black;color:white;text-align: center;font-weight: bold;font-size:18px;">Employee Details</div>
<br>
<div id="spListContainer" />
</div>
</div>
</div>`;
this._renderListAsync();
}
private _getMockListData(): Promise<ISPLists> {
return MockHttpClient.get(this.context.pageContext.web.absoluteUrl).then(()
=> {
const listData: ISPLists = {
value:
[
{ EmployeeId: 'E123', EmployeeName: 'John', Experience: 'SharePoint',Location: 'India' },
{ EmployeeId: 'E567', EmployeeName: 'Martin', Experience: '.NET',Location: 'Qatar' },
{ EmployeeId: 'E367', EmployeeName: 'Luke', Experience: 'JAVA',Location: 'UK' }
]
};
return listData;
}) as Promise<ISPLists>;
}
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
})
]
}
]
}
]
};
. }
}
Mock HTTP Client Content
The mock http client content used to test in the local workbench is as follows:
import { ISPList } from './GetSpListItemsWebPart';
export default class MockHttpClient {
private static _items: ISPList[] = [{ EmployeeId: 'E123', EmployeeName: 'John', Experience: 'SharePoint',Location: 'India' },];
public static get(restUrl: string, options?: any): Promise<ISPList[]> {
return new Promise<ISPList[]>((resolve) => {
resolve(MockHttpClient._items);
});
}
}
Test the Web part in local SharePoint Workbench
Now, we can see the output generated in the local SharePoint Workbench by running
gulp serve
command.
Since the environment is local, the mock data has been used to generate the table, as shown below.
Thus, we have successfully tested the client Web part locally.
Test the Web part in SharePoint Online
Now, let’s test the Web part in SharePoint Workbench available in SharePoint Online. This time, the 'EnvironmentType' check will evaluate to SharePoint and REST API endpoint method will be called to retrieve the list items from SharePoint list. SharePoint Online list - EmployeesList , to which we are trying to connect, using REST API is given below.
Once we have login in to SharePoint Online, we can invoke the workbench by appending the text ‘_layouts/15/workbench.aspx’ to SharePoint Online URL. As we can see below, the items have been successfully retrieved, using REST API and the data has been built into HTML table in the client Web part.
We can further modify the CSS by making changes in the �������GetSpListItems.module.scss’ file.
The Type Script solution file has been zipped and uploaded here . Feel free to work on it.