SharePoint Framework is the new development model and a lot of work has been going on with it in the past year. It went to General Availability on Feb 23, 2017. It is a page and Web part model which provides full support for client-side SharePoint development, easy integration with SharePoint data, and support for an open source tooling. With SharePoint Framework, you can use modern Web technologies and the tools in your preferred development environment to build productive experiences and apps in SharePoint.
In the previous article, we saw how to set up the development environment for SharePoint Framework. We have seen how to create and deploy the first client Web part, using SharePoint Framework here.
Create SharePoint Framework Web part project
In this article, we will be creating a client Web part, which will be retrieving the list items from SharePoint List (EmployeeList) and will display it in the tabular form in the client Web part, as shown below.
Before moving forward, ensure that SharePoint Framework development environment is ready.
Spin up Node.js command prompt, using which we will be creating the Web part 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 will have to fill up, so as 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
In order 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 up 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 GetListItemsWebPart.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
In order 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';
-
- 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);
- });
- }
- }
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 List Items
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 is able to 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>
- </div>`;
- this._renderListAsync();
- }
Test the Web part in local SharePoint Workbench
Now, we will see the output generated in the local SharePoint Workbench.
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.
I have zipped the entire solution and attached it along with the article. Feel free to work on it.
Summary
Thus, we have successfully retrieved the list items from SharePoint List ‘EmployeeList’, using REST endpoint and have displayed it in tabular form in SharePoint Framework Client Web part.