0% found this document useful (0 votes)
103 views

Getting Started With Sharepoint Framework Development Using Typescript PNP Js

Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
103 views

Getting Started With Sharepoint Framework Development Using Typescript PNP Js

Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 160

SPFx

Getting Started with


SharePoint Framework
Development using
TypeScript, PnP JS, and
React JS
About the Author
Priyaranjan KS is a Senior SharePoint Consultant engaged in architecting, designing and
developing solutions in SharePoint and Office 365. He has been working with SharePoint for the
past seven years and has worked on SharePoint 2007 through SharePoint 2016.
He is a Certified Scrum Master, as well as a Microsoft Certified Solutions Developer (SharePoint
Apps). He is a C# Corner MVP and frequently collaborates with them in the field of SharePoint.
If you need any SharePoint help, you can either find him here or drop him an email. He has
published three other free SharePoint 2016 e-books, which can be found at C# Corner.
Target Audience
The users reading the book need not have an in-depth working knowledge of SharePoint;
however, a basic working knowledge of Office 365 and SharePoint is considered ideal. All the
major solution files used in this book have been uploaded to Microsoft TechNet gallery.
Download them and use them as a reference while reading the book so that you can get a
better understanding of the structure and flow. This book is not an exhaustive walkthrough of
SharePoint Framework, but is intended to give you a head start with SharePoint Framework
Development using Typescript, PnP JS, and React JS.

Priyaranjan K S
(C# Corner MVP)
Contents

Set up SharePoint Framework Development Environment 5


Install Node JS 5
Install Yeoman and Gulp 10
Install Yeoman SharePoint Generator 11
Code Editor 12
Additional Tools for Development and Debugging 15
Fiddler 15
Postman 17
Getting Started with SharePoint Framework Development using TypeScript 18
Create the First Hello World Client Web Part 18
Create the Web Part project 18
Test the Web Part 21
SharePoint Workbench 22
Edit the Web Part 24
Add the Web Part to SharePoint 26
Create SharePoint Framework Client Web Part to Retrieve and Display List Items 28
Create the Web Part Project 29
Test the Web Part locally 32
Edit the Web Part 34
Define List Model 35
Create Mock HTTPClient to test data locally 35
Retrieve SharePoint List Items 37
Render the SharePoint List Items from Employee List 38
TS File Contents 39
Mock HTTP Client Content 42
Test the Web Part in local SharePoint Workbench 42
Test the Web Part in SharePoint Online 43
Provision Custom SharePoint List 45
Create the Web Part Project 45
Edit the Web Part 47
Package and Deploy the Solution 49
Provision SharePoint List with custom Site Columns and Content Type 54
Edit the Web Part 56
Add the Default data to SharePoint List 58
Elements.XML 58
Schema.XML 61
Update Package-Solution.json 63
Package and Deploy the Solution 65
Upgrade the Solution 72
Upgrade the Solution and Add a New List 73
Package and Deploy the Solution 77
Resolve Package Errors 78
Getting Started with PnP JS Development Using SharePoint Framework 80
Retrieve SharePoint List Items Using PnP JS and SharePoint Framework 80
Edit Web Part 82
Define List Model 83
Create Mock HTTPClient to Test Data Locally 84
Retrieve SharePoint List Items 86
Retrieve the SharePoint List Items From Employee List 86
TS File Contents to Retrieve List Data Using PnP 88
Package and Deploy the Solution 90
Test the Web Part in local SharePoint Workbench 91
Test the Web Part in SharePoint Online 92
SharePoint List Creation Using PnP and SPFx 93
Edit the Web Part 95
Install PnP JS Module 96
Create List Using PnP Method 96
TS File Code for Creating the List 97
Test the Web Part in SharePoint Online 99
Retrieve User Profile Properties Using SPFx and PnP JS 101
Create the Web Part Project 101
Edit the Web Part 102
Retrieve User Profile data 104
TS File content to retrieve User Profile Data 105
Test the Web Part in SharePoint Online 106
Retrieve SharePoint Search Results Using SPFx webpart 108
Create the Web Part Project 108
Retrieve Search Results 110
TS File Contents for Displaying the Retrieved Search Results 111
Test the Web Part in SharePoint Online 113
Implement SharePoint List item CRUD using SPFx and PnP JS 114
Create the Web Part Project 114
Edit the Web Part 115
Implement CRUD Using PnP JS 116
TS File Contents for Implementing CRUD Using PnP 117
Test the Web Part in SharePoint Online 120
Add Item 122
Update Item 123
Delete item 125
Getting Started with React JS in SharePoint 126
Retrieve SharePoint List Data Using REST API and Display Using Content Editor Web Part 126
REACT and REST API Script to Display SharePoint Data as Grid 128
Create SPFx Webpart to Retrieve SharePoint List Items Using REACT & REST API 131
Edit the Web Part 132
Exploring the File Structure 133
ReactGetItemsWebPart.ts 134
IReactgetItemsProps.TS 134
ReactGetItems/modue.scss 134
ReactGetItems.tsx 136
Test the Web Part in SharePoint Online 138
TSX File Contents for Retrieving List Items Using REST API and REACT 139
Summary 140
SharePoint Framework is the new development model in which a lot of work has been going on
in the past year. It went to General Availability on Feb 23, 2017. It is a page and Web Part
model that provides full support for client-side SharePoint development, easy integration with
SharePoint data, and support for open source tooling. With the SharePoint Framework, you can
use modern web technologies and tools in your preferred development environment to build
productive experiences and apps in SharePoint.

In this book, we will see how to set up the environment for getting started with development
using the SharePoint Framework and how to create client Web Parts using the new
development model. We will make use of TypeScript, PnP JS, and React JS to create the Web
Parts as we progress. This book will serve as a script cookbook to help you get started with
different frameworks used with SPFx.
Set Up SharePoint Framework Development
Environment
Let us see how to set up the development environment so that we can kick start it with
SharePoint Framework development. Listed below are the required components that we will
have to install in the environment.

● Node JS
● Yeoman and Gulp
● Yeoman SharePoint Generator
● Code Editor (Visual Studio Code or WebStorm)
● Postman and Fiddler (optional)

Install Node JS

Node.js is a JavaScript runtime built on Chrome's V8 JavaScript engine. It uses an event-driven,


non-blocking I/O model that makes it lightweight and efficient. Node.js's package ecosystem,
npm, is the largest ecosystem of open source libraries in the world. We will be making use of
npm along with Yeoman and Gulp to package and deploy modules.

As a first step, we will install NodeJS Long Term Support Version (LTS). We can install NodeJS
from this link .

©2017 C# CORNER.
SHARE THIS DOCUMENT AS IT IS. PLEASE DO NOT REPRODUCE, REPUBLISH, CHANGE OR COPY.
P a g e |1
Once we have downloaded the LTS version, run the executable file and proceed.

Accept the license agreement and click on “Next.”

©2017 C# CORNER.
SHARE THIS DOCUMENT AS IT IS. PLEASE DO NOT REPRODUCE, REPUBLISH, CHANGE OR COPY.
P a g e |2
We will select the Node.js runtime installation.

©2017 C# CORNER.
SHARE THIS DOCUMENT AS IT IS. PLEASE DO NOT REPRODUCE, REPUBLISH, CHANGE OR COPY.
P a g e |3
Click on “Install” to start the installation procedure.

Finally, we are finished installing NodeJS.

©2017 C# CORNER.
SHARE THIS DOCUMENT AS IT IS. PLEASE DO NOT REPRODUCE, REPUBLISH, CHANGE OR COPY.
P a g e |4
Click on the “Finish” button and restart your computer. You won’t be able to run Node.js until
you restart your computer.

If we run the NodeJS command prompt, we will get the message as shown below, which
indicates that NodeJS has been successfully installed on the local machine.

Now, let’s see the version of Node Package Manager (npm) by running the command npm –v.
It is running the V3 version.

Install Yeoman and Gulp

Yeoman is a scaffolding tool for modern web apps. It helps you to kick start new projects,
prescribing best practices and tools to help you stay productive. Often called Yo, it scaffolds out
©2017 C# CORNER.
SHARE THIS DOCUMENT AS IT IS. PLEASE DO NOT REPRODUCE, REPUBLISH, CHANGE OR COPY.
P a g e |5
a new application, writing your build configuration (e.g., Gulpfile), and pulling in relevant build
tasks and package manager dependencies (e.g., npm) that you might need for your build.

Gulp is a JavaScript task runner that helps us automate common tasks such as refreshing your
browser when you save a file, bundling and minifying libraries and CSS, and copying modified
files to an output directory. We will be using Yo and Gulp together for creating SharePoint Client
Web Parts.
Now, let’s install Yeoman and Gulp simultaneously by running the below command:

npm install -g yo gulp

We can get the version of Yeoman using the command:

yo --version

We can get the Gulp version using the command:

gulp –v

©2017 C# CORNER.
SHARE THIS DOCUMENT AS IT IS. PLEASE DO NOT REPRODUCE, REPUBLISH, CHANGE OR COPY.
P a g e |6
Install Yeoman SharePoint Generator

The Yeoman SharePoint Web Part generator helps you to quickly create a SharePoint client-
side solution project with the right tool chain and project structure. Yeoman SharePoint
Generator can be installed using the below command:

npm install -g @microsoft/generator-sharepoint@latest

We can get the version of Yeoman Generator by running the below command. As we can see,
1.0.0 indicates the General Availability version.

npm view @microsoft/generator-sharepoint version

©2017 C# CORNER.
SHARE THIS DOCUMENT AS IT IS. PLEASE DO NOT REPRODUCE, REPUBLISH, CHANGE OR COPY.
P a g e |7
Code Editor

Next, we need a code editor that will help us with editing/writing the code. We can use any code
editor or IDE that supports client-side development to build our Web Part, such as:

● Visual Studio Code


● Atom
● WebStorm

We will use Visual Studio Code in this walkthrough. You can get it here .

Once we have downloaded the exe, let us proceed with the installation.

©2017 C# CORNER.
SHARE THIS DOCUMENT AS IT IS. PLEASE DO NOT REPRODUCE, REPUBLISH, CHANGE OR COPY.
P a g e |8
Click on “Install” to start the installation procedure.

©2017 C# CORNER.
SHARE THIS DOCUMENT AS IT IS. PLEASE DO NOT REPRODUCE, REPUBLISH, CHANGE OR COPY.
P a g e |9
Finally, we have completed the installation of the Visual Studio code.

Sample screenshot:

©2017 C# CORNER.
SHARE THIS DOCUMENT AS IT IS. PLEASE DO NOT REPRODUCE, REPUBLISH, CHANGE OR COPY.
P a g e | 10
Additional Tools for Development and Debugging

Once we start the development, we must debug or test the application. Fiddler and Postman
can help us in that task.

Fiddler

Fiddler is an HTTP debugging proxy server application. It captures HTTP and HTTPS traffic and
logs it for the user to review. You can get Fiddler here

Once the executable has been downloaded, click on “Install” to set up Fiddler on your local
machine.

©2017 C# CORNER.
SHARE THIS DOCUMENT AS IT IS. PLEASE DO NOT REPRODUCE, REPUBLISH, CHANGE OR COPY.
P a g e | 11
Using Fiddler, we can examine the traffic as it is being sent or received.

Postman

Postman can be used to test SharePoint’s REST service endpoints and verify the returned data
and request headers. We can get Postman from here

©2017 C# CORNER.
SHARE THIS DOCUMENT AS IT IS. PLEASE DO NOT REPRODUCE, REPUBLISH, CHANGE OR COPY.
P a g e | 12
Postman can be added to Chrome as an app.

The REST URL can be entered in the “Request URL” field and clicking on “Send,” we can get
the SharePoint data.

©2017 C# CORNER.
SHARE THIS DOCUMENT AS IT IS. PLEASE DO NOT REPRODUCE, REPUBLISH, CHANGE OR COPY.
P a g e | 13
Thus, in this section, we saw how to set up the environment. Now, we are ready to get started
with the new SharePoint Framework development model.

©2017 C# CORNER.
SHARE THIS DOCUMENT AS IT IS. PLEASE DO NOT REPRODUCE, REPUBLISH, CHANGE OR COPY.
P a g e | 14
Getting Started With SharePoint Framework
Development Using TypeScript
In the first section of the book, we will be using TypeScript to build SharePoint Framework client
Web Parts. As we proceed further, we will see how to use React JS and PnP JS to build the
SPFx Web Parts.

Create the First “Hello World” Client Web Part

In this section, we will see how to create and deploy the first client Web Part using SharePoint
Framework. We will be creating a “Hello World” client Web Part using TypeScript to understand
the project structure and testing procedure.

Create the Web Part Project


Before moving forward, ensure that the SharePoint Framework development environment is
ready. Spin up Node.js command prompt, which we will use to create the Web Part project
structure.

We can create the directory where we will be adding the solution, using the below command:
md ClientWebPart-HelloWorld

Let’s move to the newly-created working directory.


cd ClientWebPart-HelloWorld

©2017 C# CORNER.
SHARE THIS DOCUMENT AS IT IS. PLEASE DO NOT REPRODUCE, REPUBLISH, CHANGE OR COPY.
P a g e | 15
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 project creation.

● What is your solution name?


Accept the default ClientWebPart-HelloWorld as your solution name and choose Enter.

● 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.

©2017 C# CORNER.
SHARE THIS DOCUMENT AS IT IS. PLEASE DO NOT REPRODUCE, REPUBLISH, CHANGE OR COPY.
P a g e | 16
● What is your Web Part name?
Go on and press enter to accept the default Web Part name as HelloWorld.

● Go on and press enter to accept the default Web Part description as HelloWorld
description.

Yeoman has started working on the creation of the project. It will install the required
dependencies and scaffold the solution files for the HelloWorld Web Part which will take some
time to complete. Once completed, we will get a “Congratulations” message.

©2017 C# CORNER.
SHARE THIS DOCUMENT AS IT IS. PLEASE DO NOT REPRODUCE, REPUBLISH, CHANGE OR COPY.
P a g e | 17
Test the Web Part

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. The SharePoint Framework tool chain comes with a
developer certificate that we can install for testing client Web Parts locally. From the current
Web Part directory, run the below command:

gulp trust-dev-cert

Click on “Yes” to install the certificate.

©2017 C# CORNER.
SHARE THIS DOCUMENT AS IT IS. PLEASE DO NOT REPRODUCE, REPUBLISH, CHANGE OR COPY.
P a g e | 18
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.

©2017 C# CORNER.
SHARE THIS DOCUMENT AS IT IS. PLEASE DO NOT REPRODUCE, REPUBLISH, CHANGE OR COPY.
P a g e | 19
SharePoint Workbench

SharePoint Workbench is a developer design surface that enables us to test the developed
client Web Parts without deploying them directly to SharePoint. It provides a client-side page to
which we can add the created Web Parts.

Thus, the SharePoint Workbench has opened in the browser but there are no visible Web Parts.
So, let’s go ahead and click on the Plus sign.

It will give us the option to add the Hello World Web Part that we created recently.

Upon clicking, the Web Part will be added to the page. The Web Part contains a few custom
messages.

©2017 C# CORNER.
SHARE THIS DOCUMENT AS IT IS. PLEASE DO NOT REPRODUCE, REPUBLISH, CHANGE OR COPY.
P a g e | 20
We can edit the description property directly from the UI, as shown below. However, if we want
to edit this Web Part to add more details and functionality, we must go back and terminate the
Gulp server command.

To stop Gulp from listening to the process, we can press ‘Control + C’ on our keyboard. This will
terminate the “gulp serve” command and stop the server.

©2017 C# CORNER.
SHARE THIS DOCUMENT AS IT IS. PLEASE DO NOT REPRODUCE, REPUBLISH, CHANGE OR COPY.
P a g e | 21
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\helloWorld’ location.

Run the code in the console, which will open up the Visual Studio Code editor window.

In the left pane of Visual Studio Code, we can see the project structure. The bulk of the logic
resides within the HelloWorldWebPart.ts file. Let’s add JavaScript code to add an alert message
within this TypeScript file.

©2017 C# CORNER.
SHARE THIS DOCUMENT AS IT IS. PLEASE DO NOT REPRODUCE, REPUBLISH, CHANGE OR COPY.
P a g e | 22
On clicking “Save,” Gulp will rebuild the Web Part project as shown below.

Again, running “gulp serve” will display the updated Web Part in the browser. This time, it will
display the alert message as well.

©2017 C# CORNER.
SHARE THIS DOCUMENT AS IT IS. PLEASE DO NOT REPRODUCE, REPUBLISH, CHANGE OR COPY.
P a g e | 23
Add the Web Part to SharePoint

So far, we have been testing the Web Part in SharePoint Workbench locally. Now, let’s try to
test it within the SharePoint context. SharePoint Workbench is also hosted in SharePoint Online
to preview the Web Part. It can be accessed by adding “_layouts/15/workbench.aspx” to the
SharePoint Online URL.

Expand the Plus sign and add the HelloWorld Web Part.

©2017 C# CORNER.
SHARE THIS DOCUMENT AS IT IS. PLEASE DO NOT REPRODUCE, REPUBLISH, CHANGE OR COPY.
P a g e | 24
The Web Part has triggered the alert message on the page, indicating successful hosting of the
Web Part within SharePoint.

Thus, we saw how to create a client Web Part using SharePoint Framework and test it within
SharePoint Online.

©2017 C# CORNER.
SHARE THIS DOCUMENT AS IT IS. PLEASE DO NOT REPRODUCE, REPUBLISH, CHANGE OR COPY.
P a g e | 25
Create SharePoint Framework 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 displaying it in the tabular form in the
client Web Part, as shown below.

The Solution files used in this section are zipped and uploaded to the Microsoft TechNet gallery.
Feel free to download them.

Create the Web Part Project

Spin up Node.js command prompt, using which we will be creating the Web Part project
structure.

©2017 C# CORNER.
SHARE THIS DOCUMENT AS IT IS. PLEASE DO NOT REPRODUCE, REPUBLISH, CHANGE OR COPY.
P a g e | 26
This will open the console where we can create our SharePoint Framework project structure.

We can create the directory where we will be adding the solution. Use 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

©2017 C# CORNER.
SHARE THIS DOCUMENT AS IT IS. PLEASE DO NOT REPRODUCE, REPUBLISH, CHANGE OR COPY.
P a g e | 27
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 choose 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 Web Part’s name? - We will specify it as “GetSPListItems” and press Enter.
● What is your Web Part’s description? - We will specify it as “This Web Part will retrieve
the list items from SharePoint list and display in a table.”

©2017 C# CORNER.
SHARE THIS DOCUMENT AS IT IS. PLEASE DO NOT REPRODUCE, REPUBLISH, CHANGE OR COPY.
P a g e | 28
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

©2017 C# CORNER.
SHARE THIS DOCUMENT AS IT IS. PLEASE DO NOT REPRODUCE, REPUBLISH, CHANGE OR COPY.
P a g e | 29
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 open the browser and display the client Web Part.

©2017 C# CORNER.
SHARE THIS DOCUMENT AS IT IS. PLEASE DO NOT REPRODUCE, REPUBLISH, CHANGE OR COPY.
P a g e | 30
This indicates that the project structure is set up correctly. We will now open the solution in
Visual Studio Code to add the logic for retrieving the list items from SharePoint and display
those 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.

©2017 C# CORNER.
SHARE THIS DOCUMENT AS IT IS. PLEASE DO NOT REPRODUCE, REPUBLISH, CHANGE OR COPY.
P a g e | 31
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 a list model with
SharePoint list fields in the GetSpListItemsWebPart.TS file, as shown below. Place it above the
“GetSpListItemsWebPart” class.

1. export interface ISPLists {


2. value: ISPList[];
3. }
4. export interface ISPList {
5. EmployeeId: string;
6. EmployeeName: string;
7. Experience: string;
8. Location: string;
9. }

Create Mock HTTPClient to Test Data Locally


©2017 C# CORNER.
SHARE THIS DOCUMENT AS IT IS. PLEASE DO NOT REPRODUCE, REPUBLISH, CHANGE OR COPY.
P a g e | 32
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.

1. import { ISPList } from './GetSpListItemsWebPart';


2.
3. export default class MockHttpClient {
4. private static _items: ISPList[] = [{ EmployeeId: 'E123', EmployeeName: 'John',
Experience: 'SharePoint',Location:'India' },];
5. public static get(restUrl: string, options?: any): Promise<ISPList[]> {
6. return new Promise<ISPList[]>((resolve) => {
7. resolve(MockHttpClient._items);
8. });
9. }
10. }

©2017 C# CORNER.
SHARE THIS DOCUMENT AS IT IS. PLEASE DO NOT REPRODUCE, REPUBLISH, CHANGE OR COPY.
P a g e | 33
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';”

1. import MockHttpClient from './MockHttpClient';

We will also add the mock list item retrieval method within the “GetSpListItemsWebPart” class.

1. private _getMockListData(): Promise<ISPLists> {


2. return MockHttpClient.get(this.context.pageContext.web.absoluteUrl).then(() => {
3. const listData: ISPLists = {
4. value:
5. [
6. { EmployeeId: 'E123', EmployeeName: 'John', Experience:
'SharePoint',Location: 'India' },
7. { EmployeeId: 'E567', EmployeeName: 'Martin', Experience: '.NET',Location:
'Qatar' },
8. { EmployeeId: 'E367', EmployeeName: 'Luke', Experience: 'JAVA',Location:
'UK' }
9. ]
10. };
11. return listData;
12. }) as Promise<ISPLists>;
13. }

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.

©2017 C# CORNER.
SHARE THIS DOCUMENT AS IT IS. PLEASE DO NOT REPRODUCE, REPUBLISH, CHANGE OR COPY.
P a g e | 34
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.

1. private _getListData(): Promise<ISPLists> {


2. return this.context.spHttpClient.get(this.context.pageContext.web.absoluteUrl +
`/_api/web/lists/GetByTitle('EmployeeList')/Items`, SPHttpClient.configurations.v1)
3. .then((response: Response) => {
4. debugger;
5. return response.json();
6. });
7. }

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 the
“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';

©2017 C# CORNER.
SHARE THIS DOCUMENT AS IT IS. PLEASE DO NOT REPRODUCE, REPUBLISH, CHANGE OR COPY.
P a g e | 35
We will then check Environment.type value and if it is equal to Environment.Local, the
MockHttpClient method returns the dummy data that will be called; otherwise, the method that
calls REST API to retrieve SharePoint list items will be called.

1. private _renderListAsync(): void {


2.
3. if (Environment.type === EnvironmentType.Local) {
4. this._getMockListData().then((response) => {
5. this._renderList(response.value);
6. });
7. }
8. else {
9. this._getListData()
10. .then((response) => {
11. this._renderList(response.value);
12. });
13. }
14. }

Finally, we will add the method given below, which will create an HTML table out of the retrieved
SharePoint list items.

1. private _renderList(items: ISPList[]): void {


2. let html: string = '<table class="TFtable" border=1 width=100% style="border-collapse:
collapse;">';
3. html +=
`<th>EmployeeId</th><th>EmployeeName</th><th>Experience</th><th>Location</th>`;
4. items.forEach((item: ISPList) => {
5. html += `
6. <tr>
7. <td>${item.EmployeeId}</td>
8. <td>${item.EmployeeName}</td>
9. <td>${item.Experience}</td>
10. <td>${item.Location}</td>
11. </tr>
12. `;
13. });
14. html += `</table>`;
15. const listContainer: Element = this.domElement.querySelector('#spListContainer');
16. listContainer.innerHTML = html;
17. }

©2017 C# CORNER.
SHARE THIS DOCUMENT AS IT IS. PLEASE DO NOT REPRODUCE, REPUBLISH, CHANGE OR COPY.
P a g e | 36
To enable rendering of the list items given above, we will replace the Render method in the
“GetSpListItemsWebPart” class with the code given below.

1. public render(): void {


2. this.domElement.innerHTML = `
3. <div class="${styles.helloWorld}">
4. <div class="${styles.container}">
5. <div class="ms-Grid-row ms-bgColor-themeDark ms-fontColor-white ${styles.row}">
6. <div class="ms-Grid-col ms-u-lg10 ms-u-xl8 ms-u-xlPush2 ms-u-lgPush1">
7. <span class="ms-font-xl ms-fontColor-white" style="font-size:28px">Welcome to
SharePoint Framework Development</span>
8.
9. <p class="ms-font-l ms-fontColor-white" style="text-align: center">Demo : Retrieve
Employee Data from SharePoint List</p>
10. </div>
11. </div>
12. <div class="ms-Grid-row ms-bgColor-themeDark ms-fontColor-white ${styles.row}">
13. <div style="background-color:Black;color:white;text-align: center;font-weight:
bold;font-size:18px;">Employee Details</div>
14. <br>
15. <div id="spListContainer" />
16. </div>
17. </div>
18. </div>`;
19. this._renderListAsync();
20. }

TS File Contents

The code contents used in the TS file to retrieve and display list items are given below:

1. import { Version } from '@microsoft/sp-core-library';


2. import {
3. BaseClientSideWebPart,
4. IPropertyPaneConfiguration,
5. PropertyPaneTextField
6. } from '@microsoft/sp-webpart-base';
7. import { escape } from '@microsoft/sp-lodash-subset';
8.
9. import {
10. Environment,
11. EnvironmentType

©2017 C# CORNER.
SHARE THIS DOCUMENT AS IT IS. PLEASE DO NOT REPRODUCE, REPUBLISH, CHANGE OR COPY.
P a g e | 37
12. } from '@microsoft/sp-core-library';
13.
14.
15. import styles from './GetSpListItems.module.scss';
16. import * as strings from 'getSpListItemsStrings';
17. import { IGetSpListItemsWebPartProps } from './IGetSpListItemsWebPartProps';
18. import MockHttpClient from './MockHttpClient';
19.
20. import {
21. SPHttpClient
22. } from '@microsoft/sp-http';
23.
24.
25. export interface ISPLists {
26. value: ISPList[];
27. }
28. export interface ISPList {
29. EmployeeId: string;
30. EmployeeName: string;
31. Experience: string;
32. Location: string;
33. }
34.
35. export default class GetSpListItemsWebPart extends
BaseClientSideWebPart<IGetSpListItemsWebPartProps> {
36.
37. private _getListData(): Promise<ISPLists> {
38. return this.context.spHttpClient.get(this.context.pageContext.web.absoluteUrl +
`/_api/web/lists/GetByTitle('EmployeeList')/Items`, SPHttpClient.configurations.v1)
39. .then((response: Response) => {
40. debugger;
41. return response.json();
42. });
43. }
44.
45. private _renderListAsync(): void {
46.
47. if (Environment.type === EnvironmentType.Local) {
48. this._getMockListData().then((response) => {
49. this._renderList(response.value);
50. });
51. }
52. else {
53. this._getListData()
©2017 C# CORNER.
SHARE THIS DOCUMENT AS IT IS. PLEASE DO NOT REPRODUCE, REPUBLISH, CHANGE OR COPY.
P a g e | 38
54. .then((response) => {
55. this._renderList(response.value);
56. });
57. }
58. }
59.
60. private _renderList(items: ISPList[]): void {
61. let html: string = '<table class="TFtable" border=1 width=100% style="border-collapse:
collapse;">';
62. html +=
`<th>EmployeeId</th><th>EmployeeName</th><th>Experience</th><th>Location</th>`;
63. items.forEach((item: ISPList) => {
64. html += `
65. <tr>
66. <td>${item.EmployeeId}</td>
67. <td>${item.EmployeeName}</td>
68. <td>${item.Experience}</td>
69. <td>${item.Location}</td>
70. </tr>
71. `;
72. });
73. html += `</table>`;
74. const listContainer: Element = this.domElement.querySelector('#spListContainer');
75. listContainer.innerHTML = html;
76. }
77.
78. public render(): void {
79. this.domElement.innerHTML = `
80. <div class="${styles.helloWorld}">
81. <div class="${styles.container}">
82. <div class="ms-Grid-row ms-bgColor-themeDark ms-fontColor-white ${styles.row}">
83. <div class="ms-Grid-col ms-u-lg10 ms-u-xl8 ms-u-xlPush2 ms-u-lgPush1">
84. <span class="ms-font-xl ms-fontColor-white" style="font-size:28px">Welcome to
SharePoint Framework Development</span>
85.
86. <p class="ms-font-l ms-fontColor-white" style="text-align: center">Demo : Retrieve
Employee Data from SharePoint List</p>
87. </div>
88. </div>
89. <div class="ms-Grid-row ms-bgColor-themeDark ms-fontColor-white ${styles.row}">
90. <div style="background-color:Black;color:white;text-align: center;font-weight:
bold;font-size:18px;">Employee Details</div>
91. <br>
92. <div id="spListContainer" />
©2017 C# CORNER.
SHARE THIS DOCUMENT AS IT IS. PLEASE DO NOT REPRODUCE, REPUBLISH, CHANGE OR COPY.
P a g e | 39
93. </div>
94. </div>
95. </div>`;
96. this._renderListAsync();
97. }
98.
99. private _getMockListData(): Promise<ISPLists> {
100. return MockHttpClient.get(this.context.pageContext.web.absoluteUrl).then(()
=> {
101. const listData: ISPLists = {
102. value:
103. [
104. { EmployeeId: 'E123', EmployeeName: 'John', Experience:
'SharePoint',Location: 'India' },
105. { EmployeeId: 'E567', EmployeeName: 'Martin', Experience:
'.NET',Location: 'Qatar' },
106. { EmployeeId: 'E367', EmployeeName: 'Luke', Experience:
'JAVA',Location: 'UK' }
107. ]
108. };
109. return listData;
110. }) as Promise<ISPLists>;
111. }
112.
113. protected get dataVersion(): Version {
114. return Version.parse('1.0');
115. }
116.
117. protected getPropertyPaneConfiguration(): IPropertyPaneConfiguration {
118. return {
119. pages: [
120. {
121. header: {
122. description: strings.PropertyPaneDescription
123. },
124. groups: [
125. {
126. groupName: strings.BasicGroupName,
127. groupFields: [
128. PropertyPaneTextField('description', {
129. label: strings.DescriptionFieldLabel
130. })
131. ]
132. }
©2017 C# CORNER.
SHARE THIS DOCUMENT AS IT IS. PLEASE DO NOT REPRODUCE, REPUBLISH, CHANGE OR COPY.
P a g e | 40
133. ]
134. }
135. ]
136. };
137. }
138. }

Mock HTTP Client Content

The mock HTTP client content used to test in the local Workbench is as follows:

1. import { ISPList } from './GetSpListItemsWebPart';


2.
3. export default class MockHttpClient {
4. private static _items: ISPList[] = [{ EmployeeId: 'E123', EmployeeName: 'John',
Experience: 'SharePoint',Location: 'India' },];
5. public static get(restUrl: string, options?: any): Promise<ISPList[]> {
6. return new Promise<ISPList[]>((resolve) => {
7. resolve(MockHttpClient._items);
8. });
9. }
10. }

Test the Web Part in Local SharePoint Workbench

Now, we can see the output generated in the local SharePoint Workbench by running the gulp
serve command.

©2017 C# CORNER.
SHARE THIS DOCUMENT AS IT IS. PLEASE DO NOT REPRODUCE, REPUBLISH, CHANGE OR COPY.
P a g e | 41
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 on SharePoint Online. This
time, the “EnvironmentType” check will evaluate to SharePoint and the REST API endpoint
method will be called to retrieve the list items from the SharePoint list. SharePoint Online list -
EmployeesList, to which we are trying to connect using REST API, is given below.

©2017 C# CORNER.
SHARE THIS DOCUMENT AS IT IS. PLEASE DO NOT REPRODUCE, REPUBLISH, CHANGE OR COPY.
P a g e | 42
Once we have logged 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.

©2017 C# CORNER.
SHARE THIS DOCUMENT AS IT IS. PLEASE DO NOT REPRODUCE, REPUBLISH, CHANGE OR COPY.
P a g e | 43
We can further modify the CSS by making changes in the “GetSpListItems.module.scss” file.

The TypeScript solution file has been zipped and uploaded here . Feel free to work on it.

Provision Custom SharePoint List

Next, we will see how to provision SharePoint assets using SharePoint Framework and
TypeScript. The main solution files used in this section are uploaded in Microsoft TechNet
gallery. Feel free to download it.

Create the Web Part Project

We can create the directory where we will be adding the solution, using the command given
below:
md CustomList

Let’s move to the newly created working directory, using the command:
cd CustomList

We will then create the client Web Part by running the Yeoman SharePoint Generator.
yo @microsoft/sharepoint

©2017 C# CORNER.
SHARE THIS DOCUMENT AS IT IS. PLEASE DO NOT REPRODUCE, REPUBLISH, CHANGE OR COPY.
P a g e | 44
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 “CustomList.”

On pressing Enter, we will be asked to choose 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 Web Part name? - We will specify it as “CustomList” and press Enter.
● What is your Web Part description? - We will specify it as “Custom List Created using
SharePoint Framework.”

Yeoman has started working on the scaffolding of the project. It will install the required
dependencies and scaffold the solution files for the “CustomList” Web Part which will take some
time to complete. Once completed, we will get a congratulations message.

©2017 C# CORNER.
SHARE THIS DOCUMENT AS IT IS. PLEASE DO NOT REPRODUCE, REPUBLISH, CHANGE OR COPY.
P a g e | 45
Run Code to create the scaffolding and open the project in Visual Studio Code.

©2017 C# CORNER.
SHARE THIS DOCUMENT AS IT IS. PLEASE DO NOT REPRODUCE, REPUBLISH, CHANGE OR COPY.
P a g e | 46
Edit the Web Part

Now, let’s add the folder named “SharePoint” to maintain the SharePoint files that will be
deployed as a package.

Within the SharePoint folder, let’s add another subfolder named Assets.

We will be creating an XML file - elements.xml - which will hold the information required to
provision the list. Let’s create the first supporting XML file; i.e., elements.xml.
©2017 C# CORNER.
SHARE THIS DOCUMENT AS IT IS. PLEASE DO NOT REPRODUCE, REPUBLISH, CHANGE OR COPY.
P a g e | 47
Add the below list information to the elements.xml file which contains the list name and type.
The feature Id ‘00bfea71-de22-43b2-a848-c05709900100’ refers to the custom list.

1. <?xml version="1.0" encoding="utf-8"?>


2. <Elements xmlns="http://schemas.microsoft.com/sharepoint/">
3.
4. <ListInstance
5. FeatureId="00bfea71-de22-43b2-a848-c05709900100"
6. Title="CustomList"
7. Description="Custom List Created Using SharePoint Framework"
8. TemplateType="100"
9. Url="Lists/CustomList">
10. </ListInstance>
11.
12. </Elements>

©2017 C# CORNER.
SHARE THIS DOCUMENT AS IT IS. PLEASE DO NOT REPRODUCE, REPUBLISH, CHANGE OR COPY.
P a g e | 48
Package and Deploy the Solution

Now, let’s create the deployment package by running gulp serve command from the Node.js
command prompt.

©2017 C# CORNER.
SHARE THIS DOCUMENT AS IT IS. PLEASE DO NOT REPRODUCE, REPUBLISH, CHANGE OR COPY.
P a g e | 49
This will create the sppkg package in the solutions folder, as shown below.

Take a note of the sppkg file URL by opening it in the File Explorer.

©2017 C# CORNER.
SHARE THIS DOCUMENT AS IT IS. PLEASE DO NOT REPRODUCE, REPUBLISH, CHANGE OR COPY.
P a g e | 50
We will be uploading this package to the App Catalog in the next step.

Head over to the App Catalog and upload the package.

After uploading, it will ask if we trust the package. Click on “Deploy” to add the solution.

©2017 C# CORNER.
SHARE THIS DOCUMENT AS IT IS. PLEASE DO NOT REPRODUCE, REPUBLISH, CHANGE OR COPY.
P a g e | 51
If we refresh the App Catalog page, we can see the uploaded solution.

Ensure that there are no errors for the uploaded package by checking the below columns. In
case there are some errors, we won’t be able to add the solution to the site.

Now, if we head over to the site, we can see the newly uploaded solution in the site contents.

©2017 C# CORNER.
SHARE THIS DOCUMENT AS IT IS. PLEASE DO NOT REPRODUCE, REPUBLISH, CHANGE OR COPY.
P a g e | 52
Click on it to add the solution to the site.

©2017 C# CORNER.
SHARE THIS DOCUMENT AS IT IS. PLEASE DO NOT REPRODUCE, REPUBLISH, CHANGE OR COPY.
P a g e | 53
This will add the solution to the site contents. At the same time, it will provision whatever site
assets were deployed as part of it. In our case, it is a custom list with the name “Custom List.”
We can see it from the site contents, as shown below.

The main solution files used in this section are uploaded in Microsoft TechNet gallery. Feel free
to download it.

Provision SharePoint List With Custom Site Columns and Content Type

In this section, we will see how to provision custom site columns and content type and how to
use them while provisioning a custom list. The main solution files used in this section are
uploaded in Microsoft TechNet gallery. Feel free to download it.

We can create the directory where we will be adding the solution, using the command given
below:
md ProvisionSPList

Let’s move to the newly created working directory, using the command:
cd ProvisionSPList

©2017 C# CORNER.
SHARE THIS DOCUMENT AS IT IS. PLEASE DO NOT REPRODUCE, REPUBLISH, CHANGE OR COPY.
P a g e | 54
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 “ProvisionSPList.”

On pressing enter, we will be asked to choose 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 Web Part name? - We will specify it as “ProvisionSPList”‘ and press Enter
● What is your Web Part description? - We will specify it as this Web Part will provision
SharePoint List

©2017 C# CORNER.
SHARE THIS DOCUMENT AS IT IS. PLEASE DO NOT REPRODUCE, REPUBLISH, CHANGE OR COPY.
P a g e | 55
Yeoman has started working on the scaffolding of the project. It will install the required
dependencies and scaffold the solution files for the “ProvisionSPList” Web Part, which will take
some time to complete. Once completed, we will get a congratulations message.

Edit the Web Part

Run the code to scaffold and open the project in Visual Studio Code.

©2017 C# CORNER.
SHARE THIS DOCUMENT AS IT IS. PLEASE DO NOT REPRODUCE, REPUBLISH, CHANGE OR COPY.
P a g e | 56
Now, let’s add the folder named “SharePoint” to maintain the SharePoint files that will be
deployed as a package.

Within the SharePoint folder let’s add another subfolder named Assets.

©2017 C# CORNER.
SHARE THIS DOCUMENT AS IT IS. PLEASE DO NOT REPRODUCE, REPUBLISH, CHANGE OR COPY.
P a g e | 57
We will be creating two XML files – elements.xml and schema.xml – which will hold the
information required to provision the site columns, content type, and then use them to create the
list. Let’s create the first supporting XML file, elements.xml.

Elements.xml file will contain the list information that will be used to provision the list. At first, we
will be defining the site columns using the ‘Field’ tag and then the content type that will be
deployed to the site. We will also be defining the default data that will be provisioned along with
the list.

©2017 C# CORNER.
SHARE THIS DOCUMENT AS IT IS. PLEASE DO NOT REPRODUCE, REPUBLISH, CHANGE OR COPY.
P a g e | 58
Add the Default Data to SharePoint List

We will be adding the default data within the Rows tag, as shown below.

Elements.XML

The complete code of elements.xml that is used with the project is given below:

1. <?xml version="1.0" encoding="utf-8"?>


2. <Elements xmlns="http://schemas.microsoft.com/sharepoint/">
3.
4. <Field ID="{11ED4026-1C15-4636-80EF-C27C41DB90E0}"
©2017 C# CORNER.
SHARE THIS DOCUMENT AS IT IS. PLEASE DO NOT REPRODUCE, REPUBLISH, CHANGE OR COPY.
P a g e | 59
5. Name="EmployeeName"
6. DisplayName="Employee Name"
7. Type="Text"
8. Required="FALSE"
9. Group="Employee" />
10.
11. <Field ID="{1DA0BA30-F87A-4D1B-9303-729AA02BEE25}"
12. Name="PreviousCompany"
13. DisplayName="Previous Company"
14. Type="Text"
15. Required="FALSE"
16. Group="Employee" />
17.
18. <Field ID="{145B5D00-E3AE-48EB-BB75-9699922AF8D8}"
19. Name="JoiningDate"
20. DisplayName="JoiningDate"
21. Type="DateTime"
22. Format="DateOnly"
23. Required="FALSE"
24. Group="Employee" />
25.
26. <Field ID="{197F8587-C417-458D-885E-4FBC28D1F612}"
27. Name="Expertise"
28. DisplayName="Expertise"
29. Type="Choice"
30. Required="FALSE"
31. Group="Employee">
32. <CHOICES>
33. <CHOICE>SharePoint</CHOICE>
34. <CHOICE>Java</CHOICE>
35. <CHOICE>.NET</CHOICE>
36. <CHOICE>Python</CHOICE>
37. <CHOICE>C++</CHOICE>
38. <CHOICE>Web Designer</CHOICE>
39. </CHOICES>
40. </Field>
41.
42. <Field ID="{10E72105-7577-4E9E-A758-BBBE8FF4E9BA}"
43. Name="Experience"
44. DisplayName="Experience"
45. Group="Employee"
46. Type="Number"
47. Required="False"
48. Min="0"
©2017 C# CORNER.
SHARE THIS DOCUMENT AS IT IS. PLEASE DO NOT REPRODUCE, REPUBLISH, CHANGE OR COPY.
P a g e | 60
49. Max="30"
50. Percentage="FALSE">
51. </Field>
52.
53. <ContentType ID="0x010100FA0963FA69A646AA916D2E41284FC9D1"
54. Name="EmployeeContentType"
55. Group="Employee Content Types"
56. Description="This is the Content Type for Employee Onboarding">
57. <FieldRefs>
58. <FieldRef ID="{11ED4026-1C15-4636-80EF-C27C41DB90E0}" />
59. <FieldRef ID="{1DA0BA30-F87A-4D1B-9303-729AA02BEE25}" />
60. <FieldRef ID="{145B5D00-E3AE-48EB-BB75-9699922AF8D8}" />
61. <FieldRef ID="{197F8587-C417-458D-885E-4FBC28D1F612}" />
62. <FieldRef ID="{10E72105-7577-4E9E-A758-BBBE8FF4E9BA}" />
63. </FieldRefs>
64. </ContentType>
65.
66. <ListInstance
67. CustomSchema="schema.xml"
68. FeatureId="00bfea71-de22-43b2-a848-c05709900100"
69. Title="Employee"
70. Description="Employee List created using SharePoint Framework"
71. TemplateType="100"
72. Url="Lists/Employee">
73. <Data>
74. <Rows>
75. <Row>
76. <Field Name="EmployeeName">Priyaranjan</Field>
77. <Field Name="PreviousCompany">Cognizant</Field>
78. <Field Name="JoiningDate">10/08/2010</Field>
79. <Field Name="Expertise">SharePoint</Field>
80. <Field Name="Experience">7</Field>
81. </Row>
82. <Row>
83. <Field Name="EmployeeName">Nimmy</Field>
84. <Field Name="PreviousCompany">SunTech</Field>
85. <Field Name="JoiningDate">11/04/2012</Field>
86. <Field Name="Expertise">Java</Field>
87. <Field Name="Experience">4</Field>
88. </Row>
89. <Row>
90. <Field Name="EmployeeName">Jinesh</Field>
91. <Field Name="PreviousCompany">IBM</Field>
92. <Field Name="JoiningDate">12/03/2006</Field>
©2017 C# CORNER.
SHARE THIS DOCUMENT AS IT IS. PLEASE DO NOT REPRODUCE, REPUBLISH, CHANGE OR COPY.
P a g e | 61
93. <Field Name="Expertise">.NET</Field>
94. <Field Name="Experience">11</Field>
95. </Row>
96. </Rows>
97. </Data>
98. </ListInstance>
99.
100. </Elements>

Schema.XML

Finally, we will be creating the schema.xml file which will contain the list XML. Here, we will be
adding the Content Type that we have declared in the elements.xml.

1. <ContentTypes>
2. <ContentTypeRef ID="0x010100FA0963FA69A646AA916D2E41284FC9D9" />
3. </ContentTypes>

©2017 C# CORNER.
SHARE THIS DOCUMENT AS IT IS. PLEASE DO NOT REPRODUCE, REPUBLISH, CHANGE OR COPY.
P a g e | 62
The complete schema.xml will look like below:

1. <List xmlns:ows="Microsoft SharePoint" Title="Basic List" EnableContentTypes="TRUE"


FolderCreation="FALSE" Direction="$Resources:Direction;" Url="Lists/Basic List"
BaseType="0" xmlns="http://schemas.microsoft.com/sharepoint/">
2. <MetaData>
3. <ContentTypes>
4. <ContentTypeRef ID="0x010100FA0963FA69A646AA916D2E41284FC9D9" />
5. </ContentTypes>
6. <Fields></Fields>
7. <Views>
8. <View BaseViewID="1" Type="HTML" WebPartZoneID="Main"
DisplayName="$Resources:core,objectiv_schema_mwsidcamlidC24;"
DefaultView="TRUE" MobileView="TRUE" MobileDefaultView="TRUE"
SetupPath="pages\viewpage.aspx" ImageUrl="/_layouts/images/generic.png"
Url="AllItems.aspx">
9. <XslLink Default="TRUE">main.xsl</XslLink>
10. <JSLink>clienttemplates.js</JSLink>
11. <RowLimit Paged="TRUE">30</RowLimit>
12. <Toolbar Type="Standard" />
13. <ViewFields>
14. <FieldRef Name="LinkTitle"></FieldRef>
15. <FieldRef Name="EmployeeName"></FieldRef>
16. <FieldRef Name="PreviousCompany"></FieldRef>
17. <FieldRef Name="JoiningDate"></FieldRef>
18. <FieldRef Name="Expertise"></FieldRef>
19. <FieldRef Name="Experience"></FieldRef>
20. </ViewFields>
21. <Query>
©2017 C# CORNER.
SHARE THIS DOCUMENT AS IT IS. PLEASE DO NOT REPRODUCE, REPUBLISH, CHANGE OR COPY.
P a g e | 63
22. <OrderBy>
23. <FieldRef Name="ID" />
24. </OrderBy>
25. </Query>
26. </View>
27. </Views>
28. <Forms>
29. <Form Type="DisplayForm" Url="DispForm.aspx" SetupPath="pages\form.aspx"
WebPartZoneID="Main" />
30. <Form Type="EditForm" Url="EditForm.aspx" SetupPath="pages\form.aspx"
WebPartZoneID="Main" />
31. <Form Type="NewForm" Url="NewForm.aspx" SetupPath="pages\form.aspx"
WebPartZoneID="Main" />
32. </Forms>
33. </MetaData>
34. </List>

Before we can deploy the package, we have to update the feature in the package-solution.json
file.

©2017 C# CORNER.
SHARE THIS DOCUMENT AS IT IS. PLEASE DO NOT REPRODUCE, REPUBLISH, CHANGE OR COPY.
P a g e | 64
Update Package-Solution.json

Initially the file contents will contain only the solution name. We must add the feature node to
this file as well.

Add the below contents after the version tag. Here, the id is a Visual Studio-created GUID that
identifies a unique feature.

©2017 C# CORNER.
SHARE THIS DOCUMENT AS IT IS. PLEASE DO NOT REPRODUCE, REPUBLISH, CHANGE OR COPY.
P a g e | 65
The contents of the package-solution.json will look like below.

1. {
2. "solution": {
3. "name": "provision-sp-list-client-side-solution",
4. "id": "f26589ce-0cd0-49c4-9ca3-f4a559851a0d",
5. "version": "1.0.0.0",
6. "features": [{
7. "title": "provision-sp-list-client-side-solution",
8. "description": "provision-sp-list-client-side-solution",
9. "id": "7BC1C758-F2A2-4775-B26E-DC60F8620E9A",
10. "version": "2.0.0.0",
11. "assets": {
12. "elementManifests": [
13. "elements.xml"
14. ],
15. "elementFiles":[
16. "schema.xml"
17. ]
18. }
19. }]
20. },
21. "paths": {
©2017 C# CORNER.
SHARE THIS DOCUMENT AS IT IS. PLEASE DO NOT REPRODUCE, REPUBLISH, CHANGE OR COPY.
P a g e | 66
22. "zippedPackage": "solution/provision-sp-list.sppkg"
23. }
24. }

Now, let’s package the solution using gulp bundle.

Package and Deploy the Solution

Now, we must package and bundle the solution using

gulp bundle

gulp package-solution

Thus, we are finished with the packaging of the solution.

©2017 C# CORNER.
SHARE THIS DOCUMENT AS IT IS. PLEASE DO NOT REPRODUCE, REPUBLISH, CHANGE OR COPY.
P a g e | 67
If we head over to the solutions folder, we can see the “provision-sp-list package” which we will
be uploading to SharePoint.

Make a note of the solution URL in the local computer as we will need it to upload to
SharePoint.

©2017 C# CORNER.
SHARE THIS DOCUMENT AS IT IS. PLEASE DO NOT REPRODUCE, REPUBLISH, CHANGE OR COPY.
P a g e | 68
Let’s head over to the SharePoint App Catalog site where we will be uploading the solution.

Click on “Upload” to add the solution file to the site.

©2017 C# CORNER.
SHARE THIS DOCUMENT AS IT IS. PLEASE DO NOT REPRODUCE, REPUBLISH, CHANGE OR COPY.
P a g e | 69
Click on OK to complete the upload.

It will ask to trust and deploy the solution to SharePoint.

We can see the uploaded solution in the App Catalog.

©2017 C# CORNER.
SHARE THIS DOCUMENT AS IT IS. PLEASE DO NOT REPRODUCE, REPUBLISH, CHANGE OR COPY.
P a g e | 70
Now let’s head over to the site contents and add the solution to the site.

On searching for the deployed app, it will list out the recently added solution.

©2017 C# CORNER.
SHARE THIS DOCUMENT AS IT IS. PLEASE DO NOT REPRODUCE, REPUBLISH, CHANGE OR COPY.
P a g e | 71
Click on it to add the solution to the site.

After a few seconds, we can see the newly-created custom site.

©2017 C# CORNER.
SHARE THIS DOCUMENT AS IT IS. PLEASE DO NOT REPRODUCE, REPUBLISH, CHANGE OR COPY.
P a g e | 72
Going inside it, we can see the default data that we had added to the list.

©2017 C# CORNER.
SHARE THIS DOCUMENT AS IT IS. PLEASE DO NOT REPRODUCE, REPUBLISH, CHANGE OR COPY.
P a g e | 73
The main solution files used in this section are uploaded in Microsoft TechNet gallery. Feel free
to download them.

Upgrade the Solution

Once we have deployed the solution, if we need to make some changes at a later point,
upgrade actions are available. Deploying without an upgrade will install a fresh copy of the
solution. To retain the existing data, we will go with the upgrade option. However, to do the
upgrade, we should add a new element file, say elementsV2.xml.

Upgrade the Solution and Add a New List

In our case, we are trying to add a new list along with the previously deployed solution. In the
new elements file, we will specify the list instance declaration for a custom list.

1. <?xml version="1.0" encoding="utf-8"?>


©2017 C# CORNER.
SHARE THIS DOCUMENT AS IT IS. PLEASE DO NOT REPRODUCE, REPUBLISH, CHANGE OR COPY.
P a g e | 74
2. <Elements xmlns="http://schemas.microsoft.com/sharepoint/">
3.
4. <ListInstance
5. FeatureId="00bfea71-de22-43b2-a848-c05709900100"
6. Title="ListAddedViaUpgrade"
7. Description="List added through Upgrade Action"
8. TemplateType="100"
9. Url="Lists/ListAddedViaUpgrade">
10. </ListInstance>
11.
12. </Elements>

We will also add an upgrade action which will contain the information about the newly added
elements.xml file.

©2017 C# CORNER.
SHARE THIS DOCUMENT AS IT IS. PLEASE DO NOT REPRODUCE, REPUBLISH, CHANGE OR COPY.
P a g e | 75
1. <ApplyElementManifests>
2. <ElementManifest Location="7BC1C758-F2A2-4775-B26E-
DC60F8620E9A\elementsV2.xml" />
3. </ApplyElementManifests>

As the last step we have to update the package-solution.json file by adding elementsV2.xml to
the elementsmanfiest tag and we will also add the upgrade actions file reference.

©2017 C# CORNER.
SHARE THIS DOCUMENT AS IT IS. PLEASE DO NOT REPRODUCE, REPUBLISH, CHANGE OR COPY.
P a g e | 76
©2017 C# CORNER.
SHARE THIS DOCUMENT AS IT IS. PLEASE DO NOT REPRODUCE, REPUBLISH, CHANGE OR COPY.
P a g e | 77
1. {
2. "solution": {
3. "name": "provision-sp-list-client-side-solution",
4. "id": "f26589ce-0cd0-49c4-9ca3-f4a559851a0d",
5. "version": "2.0.0.0",
6. "features": [{
7. "title": "provision-sp-list-client-side-solution",
8. "description": "provision-sp-list-client-side-solution",
9. "id": "7BC1C758-F2A2-4775-B26E-DC60F8620E9A",
10. "version": "2.0.0.0",
11. "assets": {
12. "elementManifests": [
13. "elements.xml",
14. "elementsV2.xml"
15. ],
16. "elementFiles":[
17. "schema.xml"
18. ],
19. "upgradeActions":[
20. "upgradeactionsV2.xml"
21. ]
22. }
23. }]
24. },
25. "paths": {
26. "zippedPackage": "solution/provision-sp-list.sppkg"
27. }
28. }

Package and Deploy the Solution

Save the files and run gulp serve to package the solution file. Now let’s go ahead and upload
the sppkg solution file to SharePoint App Catalog.

©2017 C# CORNER.
SHARE THIS DOCUMENT AS IT IS. PLEASE DO NOT REPRODUCE, REPUBLISH, CHANGE OR COPY.
P a g e | 78
Upon clicking on OK it will give a warning about whether or not you want to replace it with the
new solution. Click on Replace it so that the new version is added.

We can see that the version has upgraded from 1.0.0.0 to 2.0.0.0

©2017 C# CORNER.
SHARE THIS DOCUMENT AS IT IS. PLEASE DO NOT REPRODUCE, REPUBLISH, CHANGE OR COPY.
P a g e | 79
Heading over to the site contents we can see that the new list “ListAddedViaUpgrade” has been
provisioned in addition to the existing Employee list.

Resolve Package Errors

Once the solution has been uploaded to SharePoint, ensure that there are no errors mentioned
in the below columns.

©2017 C# CORNER.
SHARE THIS DOCUMENT AS IT IS. PLEASE DO NOT REPRODUCE, REPUBLISH, CHANGE OR COPY.
P a g e | 80
At times if we have some error in the package, it will be displayed as shown below. Ensure that
we resolve any such errors by analyzing the error message. The below error was thrown
because of a white space at the beginning of the Elements.XML file.

©2017 C# CORNER.
SHARE THIS DOCUMENT AS IT IS. PLEASE DO NOT REPRODUCE, REPUBLISH, CHANGE OR COPY.
P a g e | 81
Getting Started With PnP JS Development Using SharePoint
Framework
We can seamlessly integrate PnP JS file with SharePoint. The new Patterns and Practices
JavaScript Core Library was created to help developers by simplifying common operations
within SharePoint. Currently it contains a fluent API for working with the full SharePoint REST
API as well as utility and helper functions. We can use them with SharePoint Framework to work
with SharePoint with minimal effort. You can get detailed information and documentation about
PnP JS from here.

Retrieve SharePoint List Items Using PnP JS and SharePoint


Framework

As part of this article we will see how to create a SharePoint Framework Web Part that retrieves
List Items using PnP JS. The major project files used in this solution have been zipped and
uploaded at Microsoft TechNet Gallery. Feel free to download them.

We can create the directory, where we will be adding the solution, using the command given
below:
md PnPSPFrameworkGetItems

Let’s move to the newly created working directory, using the command:
cd PnPSPFrameworkGetItems

We will then create the client Web Part by running the Yeoman SharePoint Generator.
yo @microsoft/sharepoint

©2017 C# CORNER.
SHARE THIS DOCUMENT AS IT IS. PLEASE DO NOT REPRODUCE, REPUBLISH, CHANGE OR COPY.
P a g e | 82
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 “PnPSPFrameworkGetItems.”

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 Web Part name- We will specify it as “PnPSPFrameworkGetItems” and
press Enter
● What is your Web Part description- We will specify it as “Get SP Lit items using PnP.”

Yeoman has started working on the scaffolding of the project. It will install the required
dependencies and scaffold the solution files for the “PnPSPFrameworkGetItems” Web Part,
which will take some time to complete. Once completed, we will get a congratulations message.

©2017 C# CORNER.
SHARE THIS DOCUMENT AS IT IS. PLEASE DO NOT REPRODUCE, REPUBLISH, CHANGE OR COPY.
P a g e | 83
Edit Web Part

Run Code to create the scaffolding and open the project in Visual Studio Code

©2017 C# CORNER.
SHARE THIS DOCUMENT AS IT IS. PLEASE DO NOT REPRODUCE, REPUBLISH, CHANGE OR COPY.
P a g e | 84
Now we have to load the PnP JS file which we will use within the project to create a list. We will
be using npm to add PnP JS file as shown below.

npm install sp-pnp-js --save

Define List Model

Since we want to retrieve the employee list items data, we will be creating list model with
SharePoint list fields in the PnPspFrameworkGetItems.TS file, as shown below. Place it above
the “PnPspFrameworkGetItems” class.

1. export interface ISPList {


2. EmployeeId: string;
3. EmployeeName: string;
4. Experience: string;
5. Location: string;
6. }

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
PnPspFrameworkGetItemsWebPart” folder named MockHttpClient.ts, as shown below.

We will then copy the code given below into MockHttpClient.ts, as shown below.

1. import { ISPList } from './PnPspFrameworkGetItemsWebPart';


2.
3. export default class MockHttpClient {
4. private static _items: ISPList[] = [{ EmployeeId: 'E123', EmployeeName: 'John',
Experience: 'SharePoint',Location: 'India' },];
5. public static get(restUrl: string, options?: any): Promise<ISPList[]> {

©2017 C# CORNER.
SHARE THIS DOCUMENT AS IT IS. PLEASE DO NOT REPRODUCE, REPUBLISH, CHANGE OR COPY.
P a g e | 85
6. return new Promise<ISPList[]>((resolve) => {
7. resolve(MockHttpClient._items);
8. });
9. }
10. }

We can now use the MockHttpClient class in the “PnPspFrameworkGetItems” class. Let’s
import the “MockHttpClient” module by going to the PnPspFrameworkGetItemsWebPart.ts and
pasting the line given below just after “import { IPnPspFrameworkGetItemsWebPartProps } from
'./I PnPspFrameworkGetItemsWebPartProps';”

1. import MockHttpClient from './MockHttpClient';

We will also add the mock list item retrieval method within the
“PnPspFrameworkGetItemsWebPart” class.

1. private _getMockListData(): Promise<ISPList[]> {


©2017 C# CORNER.
SHARE THIS DOCUMENT AS IT IS. PLEASE DO NOT REPRODUCE, REPUBLISH, CHANGE OR COPY.
P a g e | 86
2. return MockHttpClient.get(this.context.pageContext.web.absoluteUrl).then(() => {
3. const listData: ISPList[] = [
4. { EmployeeId: 'E123', EmployeeName: 'John', Experience:
'SharePoint',Location: 'India' },
5. { EmployeeId: 'E567', EmployeeName: 'Martin', Experience: '.NET',Location:
'Qatar' },
6. { EmployeeId: 'E367', EmployeeName: 'Luke', Experience: 'JAVA',Location:
'UK' }
7. ];
8. return listData;
9. }) as Promise<ISPList[]>;
10. }

Retrieve SharePoint List Items

We will be making use of PnP library to get the list items as shown below:

1. private _getListData(): Promise<ISPList[]> {


2. return pnp.sp.web.lists.getByTitle("EmployeeList").items.get().then((response) => {
3.
4. return response;
5. });
6.
7. }

Retrieve 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 by using SharePoint Online Context. SharePoint Framework uses
“EnvironmentType” module to identify the environment where the Web Part is executed.

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
PnPspFrameworkGetItemsWebpart.ts file.

import {
Environment,
EnvironmentType
} from '@microsoft/sp-core-library';

©2017 C# CORNER.
SHARE THIS DOCUMENT AS IT IS. PLEASE DO NOT REPRODUCE, REPUBLISH, CHANGE OR COPY.
P a g e | 87
We will then check Environment.type value and if it is equal to Environment.Local, the
MockHttpClient method, which returns dummy data, will be called, otherwise the method that
calls REST API that will retrieve SharePoint list items will be called.

1. private _renderListAsync(): void {


2.
3. if (Environment.type === EnvironmentType.Local) {
4. this._getMockListData().then((response) => {
5. this._renderList(response.value);
6. });
7. }
8. else {
9. this._getListData()
10. .then((response) => {
11. this._renderList(response.value);
12. });
13. }
14. }

Finally, we will add the method given below, which will create HTML table out of the retrieved
SharePoint list items.

1. private _renderList(items: ISPList[]): void {


2. let html: string = '<table class="TFtable" border=1 width=100% style="border-collapse:
collapse;">';
3. html +=
`<th>EmployeeId</th><th>EmployeeName</th><th>Experience</th><th>Location</th>`;
4. items.forEach((item: ISPList) => {
5. html += `
6. <tr>
7. <td>${item.EmployeeId}</td>
8. <td>${item.EmployeeName}</td>
9. <td>${item.Experience}</td>
10. <td>${item.Location}</td>
11. </tr>
12. `;
13. });
14. html += `</table>`;
15. const listContainer: Element = this.domElement.querySelector('#spListContainer');
16. listContainer.innerHTML = html;
17. }

©2017 C# CORNER.
SHARE THIS DOCUMENT AS IT IS. PLEASE DO NOT REPRODUCE, REPUBLISH, CHANGE OR COPY.
P a g e | 88
To enable rendering of the list items given above, we will replace Render method in the
“PnPspFrameworkGetItemsWebPart” class with the code given below.

1. public render(): void {


2. this.domElement.innerHTML = `
3. <div class="${styles.helloWorld}">
4. <div class="${styles.container}">
5. <div class="ms-Grid-row ms-bgColor-themeDark ms-fontColor-white ${styles.row}">
6. <div class="ms-Grid-col ms-u-lg10 ms-u-xl8 ms-u-xlPush2 ms-u-lgPush1">
7. <span class="ms-font-xl ms-fontColor-white" style="font-size:28px">Welcome to
SharePoint Framework Development using PnP JS Library</span>
8.
9. <p class="ms-font-l ms-fontColor-white" style="text-align: left">Demo : Retrieve
Employee Data from SharePoint List</p>
10. </div>
11. </div>
12. <div class="ms-Grid-row ms-bgColor-themeDark ms-fontColor-white ${styles.row}">
13. <div style="background-color:Black;color:white;text-align: center;font-weight: bold;font-
size:18px;">Employee Details</div>
14. <br>
15. <div id="spListContainer" />
16. </div>
17. </div>
18. </div>`;
19. this._renderListAsync();
20. }

TS File Contents to Retrieve List Data Using PnP

The entire TS file contents that was used to implement data retrieval in the SPFx Web Part is
given below:

1. import pnp from 'sp-pnp-js';


2. import { Version } from '@microsoft/sp-core-library';
3.
4. import {
5. BaseClientSideWebPart,
6. IPropertyPaneConfiguration,
7. PropertyPaneTextField
8. } from '@microsoft/sp-webpart-base';
9. import { escape } from '@microsoft/sp-lodash-subset';
10.
11. import {
12. Environment,
©2017 C# CORNER.
SHARE THIS DOCUMENT AS IT IS. PLEASE DO NOT REPRODUCE, REPUBLISH, CHANGE OR COPY.
P a g e | 89
13. EnvironmentType
14. } from '@microsoft/sp-core-library';
15.
16. import styles from './PnPspFrameworkGetItems.module.scss';
17. import * as strings from 'pnPspFrameworkGetItemsStrings';
18. import { IPnPspFrameworkGetItemsWebPartProps } from
'./IPnPspFrameworkGetItemsWebPartProps';
19. import MockHttpClient from './MockHttpClient';
20.
21. import {
22. SPHttpClient
23. } from '@microsoft/sp-http';
24.
25.
26. export interface ISPList {
27. EmployeeId: string;
28. EmployeeName: string;
29. Experience: string;
30. Location: string;
31. }
32.
33. export default class PnPspFrameworkGetItemsWebPart extends
BaseClientSideWebPart<IPnPspFrameworkGetItemsWebPartProps> {
34.
35.
36. private _getListData(): Promise<ISPList[]> {
37. return pnp.sp.web.lists.getByTitle("EmployeeList").items.get().then((response) => {
38.
39. return response;
40. });
41.
42. }
43.
44. private _renderListAsync(): void {
45.
46. if (Environment.type === EnvironmentType.Local) {
47. this._getMockListData().then((response) => {
48. this._renderList(response);
49. });
50. }
51. else {
52. this._getListData()
53. .then((response) => {
54. this._renderList(response);
©2017 C# CORNER.
SHARE THIS DOCUMENT AS IT IS. PLEASE DO NOT REPRODUCE, REPUBLISH, CHANGE OR COPY.
P a g e | 90
55. });
56. }
57. }
58.
59. private _renderList(items: ISPList[]): void {
60. let html: string = '<table class="TFtable" border=1 width=100% style="border-collapse:
collapse;">';
61. html +=
`<th>EmployeeId</th><th>EmployeeName</th><th>Experience</th><th>Location</th>`;
62. items.forEach((item: ISPList) => {
63. html += `
64. <tr>
65. <td>${item.EmployeeId}</td>
66. <td>${item.EmployeeName}</td>
67. <td>${item.Experience}</td>
68. <td>${item.Location}</td>
69. </tr>
70. `;
71. });
72. html += `</table>`;
73. const listContainer: Element = this.domElement.querySelector('#spListContainer');
74. listContainer.innerHTML = html;
75. }
76.
77. public render(): void {
78. this.domElement.innerHTML = `
79. <div class="${styles.helloWorld}">
80. <div class="${styles.container}">
81. <div class="ms-Grid-row ms-bgColor-themeDark ms-fontColor-white ${styles.row}">
82. <div class="ms-Grid-col ms-u-lg10 ms-u-xl8 ms-u-xlPush2 ms-u-lgPush1">
83. <span class="ms-font-xl ms-fontColor-white" style="font-size:28px">Welcome to
SharePoint Framework Development using PnP JS Library</span>
84.
85. <p class="ms-font-l ms-fontColor-white" style="text-align: left">Demo : Retrieve
Employee Data from SharePoint List</p>
86. </div>
87. </div>
88. <div class="ms-Grid-row ms-bgColor-themeDark ms-fontColor-white ${styles.row}">
89. <div style="background-color:Black;color:white;text-align: center;font-weight: bold;font-
size:18px;">Employee Details</div>
90. <br>
91. <div id="spListContainer" />
92. </div>
93. </div>
©2017 C# CORNER.
SHARE THIS DOCUMENT AS IT IS. PLEASE DO NOT REPRODUCE, REPUBLISH, CHANGE OR COPY.
P a g e | 91
94. </div>`;
95. this._renderListAsync();
96. }
97.
98. private _getMockListData(): Promise<ISPList[]> {
99. return MockHttpClient.get(this.context.pageContext.web.absoluteUrl).then(() => {
100. const listData: ISPList[] = [
101. { EmployeeId: 'E123', EmployeeName: 'John', Experience:
'SharePoint',Location: 'India' },
102. { EmployeeId: 'E567', EmployeeName: 'Martin', Experience:
'.NET',Location: 'Qatar' },
103. { EmployeeId: 'E367', EmployeeName: 'Luke', Experience:
'JAVA',Location: 'UK' }
104. ];
105. return listData;
106. }) as Promise<ISPList[]>;
107. }
108.
109. protected get dataVersion(): Version {
110. return Version.parse('1.0');
111. }
112.
113. protected getPropertyPaneConfiguration(): IPropertyPaneConfiguration {
114. return {
115. pages: [
116. {
117. header: {
118. description: strings.PropertyPaneDescription
119. },
120. groups: [
121. {
122. groupName: strings.BasicGroupName,
123. groupFields: [
124. PropertyPaneTextField('description', {
125. label: strings.DescriptionFieldLabel
126. })
127. ]
128. }
129. ]
130. }
131. ]
132. };
133. }
134. }
©2017 C# CORNER.
SHARE THIS DOCUMENT AS IT IS. PLEASE DO NOT REPRODUCE, REPUBLISH, CHANGE OR COPY.
P a g e | 92
Package and Deploy the Solution

Let’s run gulp serve to package the solution.

Test the Web Part in Local SharePoint Workbench

Now, we can see the output generated in the local SharePoint Workbench.

Now let’s add the Web Part by clicking on the Plus sign.
©2017 C# CORNER.
SHARE THIS DOCUMENT AS IT IS. PLEASE DO NOT REPRODUCE, REPUBLISH, CHANGE OR COPY.
P a g e | 93
Since the environment is local, the mock data has been used to generate the table, as shown
below.

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 the PnP method will be called to
retrieve the list items from SharePoint list. Once we have logged in to SharePoint Online, we

©2017 C# CORNER.
SHARE THIS DOCUMENT AS IT IS. PLEASE DO NOT REPRODUCE, REPUBLISH, CHANGE OR COPY.
P a g e | 94
can invoke the Workbench by appending the text “_layouts/15/workbench.aspx” to SharePoint
Online URL.

It has picked up the list items from the list and displayed it as a table.

The major project files used in this solution have been zipped and uploaded at Microsoft
TechNet Gallery. Feel free to download them.

©2017 C# CORNER.
SHARE THIS DOCUMENT AS IT IS. PLEASE DO NOT REPRODUCE, REPUBLISH, CHANGE OR COPY.
P a g e | 95
SharePoint List Creation Using PnP and SPFx
In this section, we will see how to use PnP JS in SPFx to create and provision a custom list. The
major project files used in this solution have been zipped and uploaded at Microsoft TechNet
Gallery. Feel free to download them.

We can create the directory, where we will be adding the solution, using the command given
below:
md CreatePnPList

Let’s move to the newly created working directory, using the command:
cd CreatePnPList

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.

©2017 C# CORNER.
SHARE THIS DOCUMENT AS IT IS. PLEASE DO NOT REPRODUCE, REPUBLISH, CHANGE OR COPY.
P a g e | 96
● What is your solution name? : Set it to “CreatePnPList.”

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 Web Part name- We will specify it as “CreatePnPList” and press Enter
● What is your Web Part description- We will specify it as “List created using PnP JS and
SharePoint Framework.”

Yeoman has started working on the scaffolding of the project. It will install the required
dependencies and scaffold the solution files for the “CreatePnPList” Web Part, which will take
some time to complete. Once completed, we will get a congratulations message.

Edit the Web Part

Run Code to open the project in Visual Studio Code.

©2017 C# CORNER.
SHARE THIS DOCUMENT AS IT IS. PLEASE DO NOT REPRODUCE, REPUBLISH, CHANGE OR COPY.
P a g e | 97
Install PnP JS Module
Now we have to load PnP JS file which we will use within the project to create list. We will be
using npm to add PnP JS file.

npm install sp-pnp-js --save

Thus PnP js has been loaded to the project. We can refer to it in the project by using:

import { Web } from "sp-pnp-js";

©2017 C# CORNER.
SHARE THIS DOCUMENT AS IT IS. PLEASE DO NOT REPRODUCE, REPUBLISH, CHANGE OR COPY.
P a g e | 98
Create List Using PnP Method

We can create the list using PnP js method - spWeb.lists.add as shown below. We will be
creating a custom list named SPFxPnpList which has the template id : 100.

1. private CreateList(): void {


2.
3. let spWeb = new Web(this.context.pageContext.web.absoluteUrl);
4. let spListTitle = "SPFxPnPList";
5. let spListDescription = "SPFxPnP List";
6. let spListTemplateId = 100;
7. let spEnableCT = false;
8. spWeb.lists.add(spListTitle, spListDescription,spListTemplateId,
spEnableCT).then(function(splist){
9. document.getElementById("ListCreationStatus").innerHTML += `New List `+
spListTitle+ ` Created`;
10. });
11. }

Once the Web Part has been created, the status will be updated in the div.
<div id="ListCreationStatus" />

TS File Code for Creating the List

The entire code for the TS file is shown below. “this.CreateList()” method in the render method
will call the PnP list creation method and create the SharePoint list.

1. import { Web } from "sp-pnp-js";


©2017 C# CORNER.
SHARE THIS DOCUMENT AS IT IS. PLEASE DO NOT REPRODUCE, REPUBLISH, CHANGE OR COPY.
P a g e | 99
2.
3.
4.
5. import { Version } from '@microsoft/sp-core-library';
6.
7. import {
8. BaseClientSideWebPart,
9. IPropertyPaneConfiguration,
10. PropertyPaneTextField
11. } from '@microsoft/sp-webpart-base';
12. import { escape } from '@microsoft/sp-lodash-subset';
13.
14.
15. import styles from './CreatePnPList.module.scss';
16. import * as strings from 'createPnPListStrings';
17. import { ICreatePnPListWebPartProps } from './ICreatePnPListWebPartProps';
18.
19. export default class CreatePnPListWebPart extends
BaseClientSideWebPart<ICreatePnPListWebPartProps> {
20.
21. private CreateList(): void {
22.
23. let spWeb = new Web(this.context.pageContext.web.absoluteUrl);
24. let spListTitle = "SPFxPnPList";
25. let spListDescription = "SPFxPnP List";
26. let spListTemplateId = 100;
27. let spEnableCT = false;
28. spWeb.lists.add(spListTitle, spListDescription,spListTemplateId,
spEnableCT).then(function(splist){
29. document.getElementById("ListCreationStatus").innerHTML += `New List `+
spListTitle+ ` Created`;
30. });
31. }
32.
33. public render(): void {
34. this.domElement.innerHTML = `
35. <div class="${styles.helloWorld}">
36. <div class="${styles.container}">
37. <div class="ms-Grid-row ms-bgColor-themeDark ms-fontColor-white ${styles.row}">
38. <div class="ms-Grid-col ms-u-lg10 ms-u-xl8 ms-u-xlPush2 ms-u-lgPush1">
39. <span class="ms-font-xl ms-fontColor-white" style="font-size:28px">Welcome to
SharePoint Framework Development using PnP JS Library</span>
40.

©2017 C# CORNER.
SHARE THIS DOCUMENT AS IT IS. PLEASE DO NOT REPRODUCE, REPUBLISH, CHANGE OR COPY.
P a g e | 100
41. <p class="ms-font-l ms-fontColor-white" style="text-align: left">Demo : Create
SharePoint List</p>
42. </div>
43. </div>
44. <div class="ms-Grid-row ms-bgColor-themeDark ms-fontColor-white ${styles.row}">
45. <div style="background-color:Black;color:white;text-align: center;font-weight: bold;font-
size:18px;">Employee Details</div>
46. <br>
47. <div id="ListCreationStatus" />
48. </div>
49. </div>
50. </div>`;
51. this.CreateList();
52. }
53.
54. protected get dataVersion(): Version {
55. return Version.parse('1.0');
56. }
57.
58. protected getPropertyPaneConfiguration(): IPropertyPaneConfiguration {
59. return {
60. pages: [
61. {
62. header: {
63. description: strings.PropertyPaneDescription
64. },
65. groups: [
66. {
67. groupName: strings.BasicGroupName,
68. groupFields: [
69. PropertyPaneTextField('description', {
70. label: strings.DescriptionFieldLabel
71. })
72. ]
73. }
74. ]
75. }
76. ]
77. };
78. }
79. }

©2017 C# CORNER.
SHARE THIS DOCUMENT AS IT IS. PLEASE DO NOT REPRODUCE, REPUBLISH, CHANGE OR COPY.
P a g e | 101
Run gulp serve to package the solution.

Test the Web Part in SharePoint Online

Now, let’s test the Web Part in SharePoint Workbench available in SharePoint Online. Once we
have logged in to SharePoint Online, we can invoke the workbench by appending the text
“_layouts/15/workbench.aspx” to SharePoint Online URL. Add the webpart to the page by
selecting CreatePnPList icon.

This will deploy the list to SharePoint and will show a success message in the UI as shown
below.
©2017 C# CORNER.
SHARE THIS DOCUMENT AS IT IS. PLEASE DO NOT REPRODUCE, REPUBLISH, CHANGE OR COPY.
P a g e | 102
Heading over to site contents we can see the newly-created list.

©2017 C# CORNER.
SHARE THIS DOCUMENT AS IT IS. PLEASE DO NOT REPRODUCE, REPUBLISH, CHANGE OR COPY.
P a g e | 103
The major project files used in this solution have been zipped and uploaded at Microsoft
TechNet Gallery. Feel free to download them.

©2017 C# CORNER.
SHARE THIS DOCUMENT AS IT IS. PLEASE DO NOT REPRODUCE, REPUBLISH, CHANGE OR COPY.
P a g e | 104
Retrieve User Profile Properties Using SPFx and PnP
JS
In this section, we will see another example of SPFx and PnP in action, here we will be using
this combo to retrieve the user profile properties and display them in the Web Part. The major
project files used in this solution have been zipped and uploaded at Microsoft TechNet Gallery.
Feel free to download them.

Create the Web Part Project

Spin up Node.js command prompt, which we will be using to create the Web Part project
structure. We can create the directory, where we will be adding the solution, using the command
given below.
md GetUserProfileProperties

Let’s move to the newly-created working directory, using the command.


cd GetUserProfileProperties

We will then create the client Web Part by running the Yeoman SharePoint Generator.
yo @microsoft/sharepoint

©2017 C# CORNER.
SHARE THIS DOCUMENT AS IT IS. PLEASE DO NOT REPRODUCE, REPUBLISH, CHANGE OR COPY.
P a g e | 105
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 “GetUserProfileProperties.”

On pressing enter, we will be asked to choose 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 Web Part name- We will specify it as “GetUserProfileProperties” and press
Enter
● What is your Web Part description- We will specify it as “Retrieve User Properties using
SharePoint Framework.”

©2017 C# CORNER.
SHARE THIS DOCUMENT AS IT IS. PLEASE DO NOT REPRODUCE, REPUBLISH, CHANGE OR COPY.
P a g e | 106
Edit the Web Part

Run Code to open the project in Visual Studio Code

©2017 C# CORNER.
SHARE THIS DOCUMENT AS IT IS. PLEASE DO NOT REPRODUCE, REPUBLISH, CHANGE OR COPY.
P a g e | 107
Now we have to load PnP JS file which we will use within the project to create a list. We will
be using npm to add PnP JS file as shown below:

npm install sp-pnp-js --save

©2017 C# CORNER.
SHARE THIS DOCUMENT AS IT IS. PLEASE DO NOT REPRODUCE, REPUBLISH, CHANGE OR COPY.
P a g e | 108
Retrieve User Profile Data

In order to use PnP methods, we can refer to the PnP file in the project as below:

import * as pnp from 'sp-pnp-js';

We will then make use of the below function to fetch the user profile properties of the user and
display it within the Web Part. pnp.sp.profiles.myProperties.get() will return the current user’s
profile properties which can be iterated to return the required information.

1. private GetUserProperties(): void {

pnp.sp.profiles.myProperties.get().then(function(result) {
var userProperties = result.UserProfileProperties;
var userPropertyValues = "";
userProperties.forEach(function(property) {
userPropertyValues += property.Key + " - " + property.Value + "<br/>";
});
document.getElementById("spUserProfileProperties").innerHTML =
userPropertyValues;
}).catch(function(error) {
console.log("Error: " + error);
});

}
©2017 C# CORNER.
SHARE THIS DOCUMENT AS IT IS. PLEASE DO NOT REPRODUCE, REPUBLISH, CHANGE OR COPY.
P a g e | 109
TS File Contents to Retrieve User Profile Data

The entire TS file contents are as shown below. this.GetUserProperties() in the render method
will call the function that will in turn call the function that gets the User Profile properties of the
user. It will then be displayed within the div element declared in the render method.

1. import * as pnp from 'sp-pnp-js';


2.
3. import { Version } from '@microsoft/sp-core-library';
4. import {
5. BaseClientSideWebPart,
6. IPropertyPaneConfiguration,
7. PropertyPaneTextField
8. } from '@microsoft/sp-webpart-base';
9. import { escape } from '@microsoft/sp-lodash-subset';
10.
11. import styles from './GetUserProfileProperties.module.scss';
12. import * as strings from 'getUserProfilePropertiesStrings';
13. import { IGetUserProfilePropertiesWebPartProps } from
'./IGetUserProfilePropertiesWebPartProps';
14.
15. export default class GetUserProfilePropertiesWebPart extends
BaseClientSideWebPart<IGetUserProfilePropertiesWebPartProps> {
16.
17. private GetUserProperties(): void {
18.
19. pnp.sp.profiles.myProperties.get().then(function(result) {
20. var userProperties = result.UserProfileProperties;
21. var userPropertyValues = "";
22. userProperties.forEach(function(property) {
23. userPropertyValues += property.Key + " - " + property.Value + "<br/>";
24. });
25. document.getElementById("spUserProfileProperties").innerHTML =
userPropertyValues;
26. }).catch(function(error) {
27. console.log("Error: " + error);
28. });
29.
©2017 C# CORNER.
SHARE THIS DOCUMENT AS IT IS. PLEASE DO NOT REPRODUCE, REPUBLISH, CHANGE OR COPY.
P a g e | 110
30. }
31.
32. public render(): void {
33.
34. this.domElement.innerHTML = `
35. <div class="${styles.helloWorld}">
36. <div class="${styles.container}">
37. <div class="ms-Grid-row ms-bgColor-themeDark ms-fontColor-white ${styles.row}">
38. <div class="ms-Grid-col ms-u-lg10 ms-u-xl8 ms-u-xlPush2 ms-u-lgPush1">
39. <span class="ms-font-xl ms-fontColor-white" style="font-size:28px">Welcome to
SharePoint Framework Development using PnP JS Library</span>
40.
41. <p class="ms-font-l ms-fontColor-white" style="text-align: left">Demo : Retrieve User
Profile Properties</p>
42. </div>
43. </div>
44. <div class="ms-Grid-row ms-bgColor-themeDark ms-fontColor-white ${styles.row}">
45. <div style="background-color:Black;color:white;text-align: center;font-weight: bold;font-
size:18px;">User Profile Details</div>
46. <br>
47. <div id="spUserProfileProperties" />
48. </div>
49. </div>
50. </div>`;
51. this.GetUserProperties();
52. }
53.
54. protected get dataVersion(): Version {
55. return Version.parse('1.0');
56. }
57.
58. protected getPropertyPaneConfiguration(): IPropertyPaneConfiguration {
59. return {
60. pages: [
61. {
62. header: {
63. description: strings.PropertyPaneDescription
64. },
65. groups: [
66. {
67. groupName: strings.BasicGroupName,
68. groupFields: [
69. PropertyPaneTextField('description', {
70. label: strings.DescriptionFieldLabel
©2017 C# CORNER.
SHARE THIS DOCUMENT AS IT IS. PLEASE DO NOT REPRODUCE, REPUBLISH, CHANGE OR COPY.
P a g e | 111
71. })
72. ]
73. }
74. ]
75. }
76. ]
77. };
78. }
79. }

Test the Web Part in SharePoint Online

Now, let’s test the Web Part in SharePoint Workbench available in SharePoint Online. Once we
have logged in to SharePoint Online, we can invoke the workbench by appending the text
“_layouts/15/workbench.aspx” to SharePoint Online URL. Add the Web Part to the page by
selecting GetUserProfile icon.

This will add the Web Part to the page and it will fetch the user profile details of the user and
display it.

©2017 C# CORNER.
SHARE THIS DOCUMENT AS IT IS. PLEASE DO NOT REPRODUCE, REPUBLISH, CHANGE OR COPY.
P a g e | 112
The major project files used in this solution have been zipped and uploaded at Microsoft
TechNet Gallery. Feel free to download them.

©2017 C# CORNER.
SHARE THIS DOCUMENT AS IT IS. PLEASE DO NOT REPRODUCE, REPUBLISH, CHANGE OR COPY.
P a g e | 113
Retrieve SharePoint Search Results Using SPFx Web
Part
In this section, we will try to work with SharePoint Search and retrieve the search results based
on a keyword using SPFx and PnP JS.

Create the Web Part Project

Spin up Node.js command prompt, which we will use to create the Web Part project structure.
We can create the directory, where we will be adding the solution, using the command given
below:
md RetrieveSearchResults

Let’s move to the newly created working directory, using the command:
cd RetrieveSearchResults

We will then create the client Web Part by running the Yeoman SharePoint Generator:
yo @microsoft/sharepoint

©2017 C# CORNER.
SHARE THIS DOCUMENT AS IT IS. PLEASE DO NOT REPRODUCE, REPUBLISH, CHANGE OR COPY.
P a g e | 114
Run the code to create scaffolding of the project structure.

©2017 C# CORNER.
SHARE THIS DOCUMENT AS IT IS. PLEASE DO NOT REPRODUCE, REPUBLISH, CHANGE OR COPY.
P a g e | 115
The generated project structure will look like the below image:

Retrieve Search Results


Now we have to load the PnP JS file which we will use within the project to retrieve the
search results. We will be using npm to add PnP JS file as shown below:

npm install sp-pnp-js --save

We can then reference the PnP js file in the project by including the below line at the top of the
TS file:

©2017 C# CORNER.
SHARE THIS DOCUMENT AS IT IS. PLEASE DO NOT REPRODUCE, REPUBLISH, CHANGE OR COPY.
P a g e | 116
import * as pnp from 'sp-pnp-js';
import { SearchQuery, SearchResults } from "sp-pnp-js";

We can get the search results using the below function. Here we will be using the PnP method,
“pnp.sp.search” which accepts the search keyword as the parameter. It will return the search
results which we will display as a table.

1. private GetSearchresults(): void {


2.
3. pnp.sp.search("SharePoint").then((result : SearchResults) => {
4. var props = result.PrimarySearchResults;
5. debugger;
6.
7. var propValue = "";
8. var counter = 1;
9. props.forEach(function(object) {
10. propValue += counter++ +'. Title - ' +object.Title +"<br/>"+"Rank - " + object.Rank
+"<br/>"+"File Type - " + object.FileType+"<br/>"+ "Original Path - "
+object.OriginalPath +"<br/>"+" Summary - "+ object.HitHighlightedSummary +
"<br/>"+"<br/>";
11. });
12. document.getElementById("spSearchresults").innerHTML = propValue;
13. }).catch(function(err) {
14. console.log("Error: " + err);
15. });
16.
17. }

TS File Contents for Displaying the Retrieved Search Results

The entire TS file contents are as shown below. “this.GetSearchresults()” in the render method
will call the function that will retrieve the search results based on the keyword. It will then be
displayed within the div element declared in the render method.

1. import * as pnp from 'sp-pnp-js';


2. import { SearchQuery, SearchResults } from "sp-pnp-js";
3.
4. import { Version } from '@microsoft/sp-core-library';
5. import {
6. BaseClientSideWebPart,
7. IPropertyPaneConfiguration,
8. PropertyPaneTextField
©2017 C# CORNER.
SHARE THIS DOCUMENT AS IT IS. PLEASE DO NOT REPRODUCE, REPUBLISH, CHANGE OR COPY.
P a g e | 117
9. } from '@microsoft/sp-webpart-base';
10.
11. import { escape } from '@microsoft/sp-lodash-subset';
12.
13. import styles from './RetrieveSearchResults.module.scss';
14. import * as strings from 'retrieveSearchResultsStrings';
15. import { IRetrieveSearchResultsWebPartProps } from
'./IRetrieveSearchResultsWebPartProps';
16.
17. export default class RetrieveSearchResultsWebPart extends
BaseClientSideWebPart<IRetrieveSearchResultsWebPartProps> {
18. private GetSearchresults(): void {
19.
20. pnp.sp.search("SharePoint").then((result : SearchResults) => {
21. var props = result.PrimarySearchResults;
22. debugger;
23.
24. var propValue = "";
25. var counter = 1;
26. props.forEach(function(object) {
27. propValue += counter++ +'. Title - ' +object.Title +"<br/>"+"Rank - " + object.Rank
+"<br/>"+"File Type - " + object.FileType+"<br/>"+ "Original Path - "
+object.OriginalPath +"<br/>"+" Summary - "+ object.HitHighlightedSummary +
"<br/>"+"<br/>";
28. });
29. document.getElementById("spSearchresults").innerHTML = propValue;
30. }).catch(function(err) {
31. console.log("Error: " + err);
32. });
33.
34. }
35.
36.
37. public render(): void {
38.
39. this.domElement.innerHTML = `
40. <div class="${styles.helloWorld}">
41. <div class="${styles.container}">
42. <div class="ms-Grid-row ms-bgColor-themeDark ms-fontColor-white ${styles.row}">
43. <div class="ms-Grid-col ms-u-lg10 ms-u-xl8 ms-u-xlPush2 ms-u-lgPush1">
44. <span class="ms-font-xl ms-fontColor-white" style="font-size:28px">Welcome to
SharePoint Framework Development using PnP JS Library</span>
45.

©2017 C# CORNER.
SHARE THIS DOCUMENT AS IT IS. PLEASE DO NOT REPRODUCE, REPUBLISH, CHANGE OR COPY.
P a g e | 118
46. <p class="ms-font-l ms-fontColor-white" style="text-align: left">Demo : Retrieve
SharePoint Search Result</p>
47. </div>
48. </div>
49. <div class="ms-Grid-row ms-bgColor-themeDark ms-fontColor-white ${styles.row}">
50. <div style="background-color:Black;color:white;text-align: center;font-weight: bold;font-
size:18px;">Search Results </div>
51. <br>
52. <div id="spSearchresults" />
53. </div>
54. </div>
55. </div>`;
56. this.GetSearchresults();
57. }
58.
59. protected get dataVersion(): Version {
60. return Version.parse('1.0');
61. }
62.
63. protected getPropertyPaneConfiguration(): IPropertyPaneConfiguration {
64. return {
65. pages: [
66. {
67. header: {
68. description: strings.PropertyPaneDescription
69. },
70. groups: [
71. {
72. groupName: strings.BasicGroupName,
73. groupFields: [
74. PropertyPaneTextField('description', {
75. label: strings.DescriptionFieldLabel
76. })
77. ]
78. }
79. ]
80. }
81. ]
82. };
83. }
84. }

©2017 C# CORNER.
SHARE THIS DOCUMENT AS IT IS. PLEASE DO NOT REPRODUCE, REPUBLISH, CHANGE OR COPY.
P a g e | 119
Test the Web Part in SharePoint Online

Now, let’s test the Web Part in SharePoint Workbench available in SharePoint Online. Once we
have logged in to SharePoint Online, we can invoke the Workbench by appending the text
“_layouts/15/workbench.aspx” to SharePoint Online URL. Add the Web Part to the page by
selecting the “RetrieveSearchResults” icon.

Thus, the search results have been retrieved and they have been listed in the Web Part as
shown below.

©2017 C# CORNER.
SHARE THIS DOCUMENT AS IT IS. PLEASE DO NOT REPRODUCE, REPUBLISH, CHANGE OR COPY.
P a g e | 120
The major project files used in this solution have been zipped and uploaded at Microsoft
TechNet Gallery. Feel free to download them.

©2017 C# CORNER.
SHARE THIS DOCUMENT AS IT IS. PLEASE DO NOT REPRODUCE, REPUBLISH, CHANGE OR COPY.
P a g e | 121
Implement SharePoint List Item CRUD Using SPFx
and PnP JS
In this section, we will see how to create a Web Part that does Create/Read/Update/Delete
operations against SharePoint List items using SPFx and PnP JS. The major project files used
in this solution have been zipped and uploaded at Microsoft TechNet Gallery. Feel free to
download them.

Create the Web Part Project

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 PnPSPCRUD

Let’s move to the newly-created working directory, using the command:


cd PnPSPCRUD

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 “PnPSPCRUD.”

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 Web Part name- We will specify it as “PnPSPCRUD” and press Enter
● What is your Web Part description - We will specify it as “This Web Part will perform
CRUD operations using PnP and SPFx.”

Edit the Web Part

Run Code to create the scaffolding and open the project in Visual Studio Code

©2017 C# CORNER.
SHARE THIS DOCUMENT AS IT IS. PLEASE DO NOT REPRODUCE, REPUBLISH, CHANGE OR COPY.
P a g e | 122
Now we have to load PnP JS file which we will use within the project to create the list. We
will be using npm to add PnP JS file:

npm install sp-pnp-js --save

Implement CRUD Using PnP JS

In order to use PnP methods,we can refer to the PnP file in the project as below:

import * as pnp from 'sp-pnp-js';

We will then add CRUD buttons in the render method so that the UI looks like the below image.

©2017 C# CORNER.
SHARE THIS DOCUMENT AS IT IS. PLEASE DO NOT REPRODUCE, REPUBLISH, CHANGE OR COPY.
P a g e | 123
Each button will have an event listener which will be invoked on the button click.

1. <button id="AddItem" type="submit" >Add</button>


2. <button id="UpdateItem" type="submit" >Update</button>
3. <button id="DeleteItem" type="submit" >Delete</button>

The event listeners will be added as:

1. private AddEventListeners() : void{


2. document.getElementById('AddItem').addEventListener('click',()=>this.AddItem());
3.
document.getElementById('UpdateItem').addEventListener('click',()=>this.UpdateItem());
4. document.getElementById('DeleteItem').addEventListener('click',()=>this.DeleteItem());
5. }

Each of these methods will use PnP to implement the CRUD operations as:

1. AddItem()
2. {
3.
4. pnp.sp.web.lists.getByTitle('EmployeeList').items.add({
5. EmployeeName : document.getElementById('EmployeeName')["value"],
6. Experience : document.getElementById('Experience')["value"],
7. Location:document.getElementById('Location')["value"]
8. });
9. alert("Record with Employee Name : "+
document.getElementById('EmployeeName')["value"] + " Added !");
10.
11. }
©2017 C# CORNER.
SHARE THIS DOCUMENT AS IT IS. PLEASE DO NOT REPRODUCE, REPUBLISH, CHANGE OR COPY.
P a g e | 124
12.
13. UpdateItem()
14. {
15.
16. var id = document.getElementById('EmployeeId')["value"];
17. pnp.sp.web.lists.getByTitle("EmployeeList").items.getById(id).update({
18. EmployeeName : document.getElementById('EmployeeName')["value"],
19. Experience : document.getElementById('Experience')["value"],
20. Location:document.getElementById('Location')["value"]
21. });
22. alert("Record with Employee Name : "+
document.getElementById('EmployeeName')["value"] + " Updated !");
23. }
24.
25. DeleteItem()
26. {
27.
pnp.sp.web.lists.getByTitle("EmployeeList").items.getById(document.getElementById('E
mployeeId')["value"]).delete();
28. alert("Record with Employee ID : "+ document.getElementById('EmployeeId')["value"]
+ " Deleted !");
29. }

TS File Contents for Implementing CRUD Using PnP

The entire TS file contents are as shown below, this.getListData(); this.AddEventListeners();


in the render method will first call the function that will retrieve the list items and display within
the div element declared in the render method. AddEventListeners will bind the button events to
respective functions which get called upon the button clicks.

1. import pnp from 'sp-pnp-js';


2.
3. import { Version } from '@microsoft/sp-core-library';
4. import {
5. BaseClientSideWebPart,
6. IPropertyPaneConfiguration,
7. PropertyPaneTextField
8. } from '@microsoft/sp-webpart-base';
9. import { escape } from '@microsoft/sp-lodash-subset';
10.
11. import styles from './PnPspCrud.module.scss';
12. import * as strings from 'pnPspCrudStrings';
©2017 C# CORNER.
SHARE THIS DOCUMENT AS IT IS. PLEASE DO NOT REPRODUCE, REPUBLISH, CHANGE OR COPY.
P a g e | 125
13. import { IPnPspCrudWebPartProps } from './IPnPspCrudWebPartProps';
14.
15. export interface ISPList {
16. ID: string;
17. EmployeeName: string;
18. Experience: string;
19. Location: string;
20. }
21.
22. export default class PnPspCrudWebPart extends
BaseClientSideWebPart<IPnPspCrudWebPartProps> {
23.
24.
25. private AddEventListeners() : void{
26. document.getElementById('AddItem').addEventListener('click',()=>this.AddItem());
27.
document.getElementById('UpdateItem').addEventListener('click',()=>this.UpdateItem());
28. document.getElementById('DeleteItem').addEventListener('click',()=>this.DeleteItem());
29. }
30.
31. private _getListData(): Promise<ISPList[]> {
32. return pnp.sp.web.lists.getByTitle("EmployeeList").items.get().then((response) => {
33.
34. return response;
35. });
36.
37. }
38.
39. private getListData(): void {
40.
41. this._getListData()
42. .then((response) => {
43. this._renderList(response);
44. });
45. }
46.
47. private _renderList(items: ISPList[]): void {
48. let html: string = '<table class="TFtable" border=1 width=100% style="border-collapse:
collapse;">';
49. html +=
`<th>EmployeeId</th><th>EmployeeName</th><th>Experience</th><th>Location</th>`;
50. items.forEach((item: ISPList) => {
51. html += `
52. <tr>
©2017 C# CORNER.
SHARE THIS DOCUMENT AS IT IS. PLEASE DO NOT REPRODUCE, REPUBLISH, CHANGE OR COPY.
P a g e | 126
53. <td>${item.ID}</td>
54. <td>${item.EmployeeName}</td>
55. <td>${item.Experience}</td>
56. <td>${item.Location}</td>
57. </tr>
58. `;
59. });
60. html += `</table>`;
61. const listContainer: Element = this.domElement.querySelector('#spGetListItems');
62. listContainer.innerHTML = html;
63. }
64.
65.
66.
67. public render(): void {
68. this.domElement.innerHTML = `
69.
70. <div class="parentContainer" style="background-color: lightgrey">
71. <div class="ms-Grid-row ms-bgColor-themeDark ms-fontColor-white ${styles.row}">
72. <div class="ms-Grid-col ms-u-lg10 ms-u-xl8 ms-u-xlPush2 ms-u-lgPush1">
73. <span class="ms-font-xl ms-fontColor-white" style="font-size:28px">Welcome to
SharePoint Framework Development using PnP JS Library</span>
74. <p class="ms-font-l ms-fontColor-white" style="text-align: left">Demo : SharePoint
List CRUD using PnP JS and SPFx</p>
75. </div>
76. </div>
77. <div class="ms-Grid-row ms-bgColor-themeDark ms-fontColor-white ${styles.row}">
78. <div style="background-color:Black;color:white;text-align: center;font-weight: bold;font-
size:18px;">Employee Details</div>
79.
80. </div>
81. <div style="background-color: lightgrey" >
82. <form >
83. <br>
84. <div data-role="header">
85. <h3>Add SharePoint List Items</h3>
86. </div>
87. <div data-role="main" class="ui-content">
88. <div >
89. <input id="EmployeeName" placeholder="EmployeeName" />
90. <input id="Experience" placeholder="Experience" />
91. <input id="Location" placeholder="Location" />
92. </div>
93. <div></br></div>
©2017 C# CORNER.
SHARE THIS DOCUMENT AS IT IS. PLEASE DO NOT REPRODUCE, REPUBLISH, CHANGE OR COPY.
P a g e | 127
94. <div >
95. <button id="AddItem" type="submit" >Add</button>
96. </div>
97. </div>
98. <div data-role="header">
99. <h3>Update/Delete SharePoint List Items</h3>
100. </div>
101. <div data-role="main" class="ui-content">
102. <div >
103. <input id="EmployeeId" placeholder="EmployeeId" />
104. </div>
105. <div></br></div>
106. <div >
107. <button id="UpdateItem" type="submit" >Update</button>
108. <button id="DeleteItem" type="submit" >Delete</button>
109. </div>
110. </div>
111. </form>
112. </div>
113. <br>
114. <div style="background-color: lightgrey" id="spGetListItems" />
115. </div>
116.
117. `;
118. this.getListData();
119. this.AddEventListeners();
120. }
121.
122. AddItem()
123. {
124.
125. pnp.sp.web.lists.getByTitle('EmployeeList').items.add({
126. EmployeeName : document.getElementById('EmployeeName')["value"],
127. Experience : document.getElementById('Experience')["value"],
128. Location:document.getElementById('Location')["value"]
129. });
130. alert("Record with Employee Name : "+
document.getElementById('EmployeeName')["value"] + " Added !");
131.
132. }
133.
134. UpdateItem()
135. {
136.
©2017 C# CORNER.
SHARE THIS DOCUMENT AS IT IS. PLEASE DO NOT REPRODUCE, REPUBLISH, CHANGE OR COPY.
P a g e | 128
137. var id = document.getElementById('EmployeeId')["value"];
138. pnp.sp.web.lists.getByTitle("EmployeeList").items.getById(id).update({
139. EmployeeName : document.getElementById('EmployeeName')["value"],
140. Experience : document.getElementById('Experience')["value"],
141. Location:document.getElementById('Location')["value"]
142. });
143. alert("Record with Employee Name : "+
document.getElementById('EmployeeName')["value"] + " Updated !");
144. }
145.
146. DeleteItem()
147. {
148.
pnp.sp.web.lists.getByTitle("EmployeeList").items.getById(document.getElementById('E
mployeeId')["value"]).delete();
149. alert("Record with Employee ID : "+
document.getElementById('EmployeeId')["value"] + " Deleted !");
150. }
151.
152. protected get dataVersion(): Version {
153. return Version.parse('1.0');
154. }
155.
156. protected getPropertyPaneConfiguration(): IPropertyPaneConfiguration {
157. return {
158. pages: [
159. {
160. header: {
161. description: strings.PropertyPaneDescription
162. },
163. groups: [
164. {
165. groupName: strings.BasicGroupName,
166. groupFields: [
167. PropertyPaneTextField('description', {
168. label: strings.DescriptionFieldLabel
169. })
170. ]
171. }
172. ]
173. }
174. ]
175. };
176. }
©2017 C# CORNER.
SHARE THIS DOCUMENT AS IT IS. PLEASE DO NOT REPRODUCE, REPUBLISH, CHANGE OR COPY.
P a g e | 129
177. }

Test the Web Part in SharePoint Online

Now, let’s test the Web Part in SharePoint Workbench available in SharePoint Online. Run gulp
serve in the Node Command line and head over to the SharePoint Online Site. Once we log in
to SharePoint Online, we can invoke the Workbench by appending the text
“_layouts/15/workbench.aspx” to SharePoint Online URL. Add the Web Part to the page by
selecting the “PnPspCRUD” icon.

The UI will look like the below image:

©2017 C# CORNER.
SHARE THIS DOCUMENT AS IT IS. PLEASE DO NOT REPRODUCE, REPUBLISH, CHANGE OR COPY.
P a g e | 130
Add Item

We can input the details and save it to the list by clicking on Add which will create a new list
item using the PnP Add method.

©2017 C# CORNER.
SHARE THIS DOCUMENT AS IT IS. PLEASE DO NOT REPRODUCE, REPUBLISH, CHANGE OR COPY.
P a g e | 131
On Clicking on Add, the new item has been added to the SharePoint List.

The table has listed the new item at the bottom of the list.

©2017 C# CORNER.
SHARE THIS DOCUMENT AS IT IS. PLEASE DO NOT REPRODUCE, REPUBLISH, CHANGE OR COPY.
P a g e | 132
Update Item

Similarly, we can update the existing list item by adding the data and providing the list item id
which will be used to pick the item from the list and update it.

On Clicking on Update, the list item has been updated.

©2017 C# CORNER.
SHARE THIS DOCUMENT AS IT IS. PLEASE DO NOT REPRODUCE, REPUBLISH, CHANGE OR COPY.
P a g e | 133
The location column value of the list item has been changed and reflected in the table as shown
below.

©2017 C# CORNER.
SHARE THIS DOCUMENT AS IT IS. PLEASE DO NOT REPRODUCE, REPUBLISH, CHANGE OR COPY.
P a g e | 134
Delete item

We can make use of the PnP delete method to delete the item from the list by providing the item
id as shown below.

The major project files used in this solution have been zipped and uploaded at Microsoft
TechNet Gallery. Feel free to download them.

©2017 C# CORNER.
SHARE THIS DOCUMENT AS IT IS. PLEASE DO NOT REPRODUCE, REPUBLISH, CHANGE OR COPY.
P a g e | 135
Getting Started With React JS in SharePoint

React makes it easy to create interactive UIs. It helps us to create simple views for each state in
our application, and efficiently update and render the right components when our data changes.
In this section, we will make use of React and REST API to retrieve list items from SharePoint
and display them using the SPFx Web Part.

Retrieve SharePoint List Data Using REST API and Display


Using Content Editor Web Part

Elements are the smallest building blocks of React apps. They describe what we want to see
on the UI. For example:

const element = <h1>Display me at root node</h1>;

reactdom.render is the starting point of the React component. Let's say we have a <div>
somewhere in our HTML file:

<div id="root"></div>

So to render our React element into the above root DOM node, we will pass both to
ReactDOM.render() as :

const element = <h1>Display me at root node</h1>;


ReactDOM.render(
element,
document.getElementById('root')
);

This will display the message at root div. In our case we will be displaying the data retrieved
from the “ProductSales” list in the div named “CarSalesData.”

ReactDOM.render(<ReactSP />, document.getElementById('CarSalesData'));

ReactSP represents the component that will be rendered at the CarSalesData div. ReactSP,
which is the component name, is defined as plain Javascript class which extends
React.Component abstract class. We will also define at least one render method within it and
will be defining the UI within this render method.

Within the class we will also have a constructor, which is the right place to initialize state. We
will
©2017 C# CORNER.
SHARE THIS DOCUMENT AS IT IS. PLEASE DO NOT REPRODUCE, REPUBLISH, CHANGE OR COPY.
P a g e | 136
update this state with SharePoint data at a later point in the React lifecycle. If we don't have to
initialize state and we are not binding any methods, we don't need to implement a constructor
for our React component.

Each component has several "lifecycle methods" that we can override to run code at a particular
time of the process. Methods that are prefixed with “will” are called just before some event
happens, and methods prefixed with “did” are called just after an event happens. We will be
making use of the 'componentDidMount' method to fetch data from SharePoint List and we will
update the state with this data. In the render method, we will then read the state data and
display it in the UI.

©2017 C# CORNER.
SHARE THIS DOCUMENT AS IT IS. PLEASE DO NOT REPRODUCE, REPUBLISH, CHANGE OR COPY.
P a g e | 137
REACT and REST API Script to Display SharePoint Data as Grid

The code can be saved as a text file and added to the Content Editor Webpart to display the
grid Web Part.

1. <script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.5.4/react.js"></script>
2. <script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.5.4/react-
dom.min.js"></script>
3. <script src="https://cdnjs.cloudflare.com/ajax/libs/babel-
standalone/6.24.0/babel.min.js"></script>
4. <div id="CarSalesData"></div>
5. <script type="text/babel">
6. var tableStyle = {
7. display: "table",
8. marginLeft : "40px"
9. }
10. var panelStyle = {
11. background: "#91A4A7"
12. }
13.
14. var divStyle = {
15. background: "#eee",
16. padding: "20px",
17. margin: "20px"
18. };
19.
20. var headerCaptionStyle = {
21. background: "#4B6978",
22. display: "table-cell",
23. border: "solid",
24. textAlign : "center",
25. width : "500px",
26. height : "30px",
27. paddingTop : "3px",
28. color : "white",
29. marginLeft : "80px",
30. display : "block"
31. };
32.
33. var headerStyle = {
34. background: "#4B6978",
35. display: "table-cell",
36. border: "solid",
©2017 C# CORNER.
SHARE THIS DOCUMENT AS IT IS. PLEASE DO NOT REPRODUCE, REPUBLISH, CHANGE OR COPY.
P a g e | 138
37. textAlign : "center",
38. width : "100px",
39. height : "30px",
40. paddingTop : "10px",
41. color : "white"
42. };
43.
44. var tableCaptionStyle = {
45. background: "#c6e2ff",
46. display: "block",
47. fontSize : "20px",
48. fontWeight: "bold",
49. border: "solid",
50. textAlign : "center",
51. width : "650px",
52. height : "30px",
53. paddingTop : "3px",
54. borderRadius: "25px",
55. marginLeft : "30px",
56. marginTop : "20px"
57. }
58.
59.
60. var rowCaptionStyle = {
61. width : "600px",
62. display : "table-caption",
63. background: "#4B6978",
64. textAlign : "center",
65. padding: "20px",
66. fontSize : "20px",
67. fontWeight :"bold",
68. color : "white"
69. };
70.
71. var rowStyle = {
72. display : "table-row",
73. background: "#eee",
74. padding: "20px",
75. margin: "20px",
76. fontWeight :"bold"
77. };
78.
79. var CellStyle = {
80. display: "table-cell",
©2017 C# CORNER.
SHARE THIS DOCUMENT AS IT IS. PLEASE DO NOT REPRODUCE, REPUBLISH, CHANGE OR COPY.
P a g e | 139
81. border: "solid",
82. borderColor : "white",
83. textAlign : "center",
84. width : "100px",
85. height : "30px",
86. paddingTop : "10px"
87.
88. }
89.
90. class ReactSP extends React.Component{
91. debugger;
92. constructor(){
93. super();
94. this.state = {
95. items: [
96. {
97. "CarName": "",
98. "Quarter1": "",
99. "Quarter2":"",
100. "Quarter3": "",
101. "Quarter4":""
102. }
103. ]
104. };
105.
106. }
107.
108. componentDidMount() {
109. debugger;
110. this.RetrieveSPData();
111. }
112.
113. RetrieveSPData(){
114. var reactHandler = this;
115.
116. var spRequest = new XMLHttpRequest();
117. spRequest.open('GET',
"/sites/playground/_api/web/lists/getbytitle('ProductSales')/items",true);
118. spRequest.setRequestHeader("Accept","application/json");
119.
120. spRequest.onreadystatechange = function(){
121.
122. if (spRequest.readyState === 4 && spRequest.status === 200){
123. var result = JSON.parse(spRequest.responseText);
©2017 C# CORNER.
SHARE THIS DOCUMENT AS IT IS. PLEASE DO NOT REPRODUCE, REPUBLISH, CHANGE OR COPY.
P a g e | 140
124.
125. reactHandler.setState({
126. items: result.value
127. });
128. }
129. else if (spRequest.readyState === 4 && spRequest.status !== 200){
130. console.log('Error Occured !');
131. }
132. };
133. spRequest.send();
134. }
135.
136. render(){
137. debugger;
138. return (
139. <div style={panelStyle}>
140. <br></br>
141.
142. <br></br>
143. <div style={tableCaptionStyle} > Demo : Retrieve SharePoint List Items
using React JS </div>
144. <br></br>
145.
146. <div style={tableStyle} >
147. <div style={rowCaptionStyle} > Quarterly Car Sales Data </div>
148. <div style={rowStyle} >
149. <div style={headerStyle}>Car Name</div>
150. <div style={headerStyle}>Quarter 1 </div>
151. <div style={headerStyle}>Quarter 2</div>
152. <div style={headerStyle}>Quarter 3</div>
153. <div style={headerStyle}>Quarter 4</div>
154. </div>
155.
156. {this.state.items.map(function(item,key){
157.
158. return (<div style={rowStyle} key={key}>
159. <div style={CellStyle}>{item.CarName}</div>
160. <div style={CellStyle}>{item.Quarter1}</div>
161. <div style={CellStyle}>{item.Quarter2}</div>
162. <div style={CellStyle}>{item.Quarter3}</div>
163. <div style={CellStyle}>{item.Quarter4}</div>
164. </div>);
165. })}
166.
©2017 C# CORNER.
SHARE THIS DOCUMENT AS IT IS. PLEASE DO NOT REPRODUCE, REPUBLISH, CHANGE OR COPY.
P a g e | 141
167. </div>
168. </div>
169.
170. );
171. }
172.
173.
174. }
175.
176. ReactDOM.render(<ReactSP />, document.getElementById('CarSalesData'));
177. </script>

©2017 C# CORNER.
SHARE THIS DOCUMENT AS IT IS. PLEASE DO NOT REPRODUCE, REPUBLISH, CHANGE OR COPY.
P a g e | 142
Create SPFx Webpart to Retrieve SharePoint List
Items Using REACT and REST API
In this section, we will see how to create a client Web Part using SharePoint Framework and
React JS that displays SharePoint List data retrieved using REST API. The major project files
used in this solution have been zipped and uploaded at Microsoft TechNet Gallery. Feel free to
download them.

Let’s get started with the creation of the project by creating a directory.

md REACTGetItems
cd REACTGetItems

Run the yeoman generator using the command ‘yo @microsoft/sharepoint’

©2017 C# CORNER.
SHARE THIS DOCUMENT AS IT IS. PLEASE DO NOT REPRODUCE, REPUBLISH, CHANGE OR COPY.
P a g e | 143
Edit the Web Part

Run the code to create the scaffolding and open the project in Visual Studio Code. We will need
jQuery to make Ajax REST API calls. So let’s install jQuery using NPM as shown below:

npm install --save jquery


npm install --save @types/jquery

Later we will import them to the solution in the ReactGetItems.tsx file using:
import * as jquery from “jquery”;

©2017 C# CORNER.
SHARE THIS DOCUMENT AS IT IS. PLEASE DO NOT REPRODUCE, REPUBLISH, CHANGE OR COPY.
P a g e | 144
Exploring the File Structure

©2017 C# CORNER.
SHARE THIS DOCUMENT AS IT IS. PLEASE DO NOT REPRODUCE, REPUBLISH, CHANGE OR COPY.
P a g e | 145
We will be making use of the above marked files to implement the solution using React.

● IReactgetItemsProps.TS : This will hold the properties that will be accessed by other
files in the solution. By default, there is a description property defined, we will add
another property “siteURL” as well, using the interface.
● ReactGetItems/modue.scss: This will contain the css styles that are used within the TSX
file.
● ReactGetItems.tsx: This file serves as the major location where the UI and logics are
defined.
● ReactGetItemsWebPart.ts: This acts as the starting point of the control flow and data
rendering phase, which is initiated from this file using the ReactDom.render method.

ReactGetItemsWebPart.ts

The rendering of the Web Part is initiated from the ReactGetItemsWebPart TS file . Here
ReactDom.render method takes the first parameter as the element that should be rendered
(after processing some logic) at the second parameter. The element is defined by the class
“ReactGetItems.” ReactGetItems extends React.Component in the ReactGetItems.tsx file that
contains the major logic processing and UI.

1. export default class ReactGetItemsWebPart extends


BaseClientSideWebPart<IReactGetItemsWebPartProps> {
2.
3. public render(): void {
4. const element: React.ReactElement<IReactGetItemsProps > = React.createElement(
5. ReactGetItems,
6. {
7. description: this.properties.description,
8. siteurl: this.context.pageContext.web.absoluteUrl
9. }
10. );
11.
12. ReactDom.render(element, this.domElement);
13. }

IReactgetItemsProps.TS

This file contains the properties that will be accessed across the files and are declared using an
Interface as shown below:

1. export interface IReactGetItemsProps {


2. description: string;
3. siteurl: string;

©2017 C# CORNER.
SHARE THIS DOCUMENT AS IT IS. PLEASE DO NOT REPRODUCE, REPUBLISH, CHANGE OR COPY.
P a g e | 146
4. }

ReactGetItems/modue.scss

The CSS style used by the Web Part is defined within this file. The CSS used for our Web Part
is given below:

1. .tableStyle{
2. display: table ;
3. margin-left : 100px ;
4. }
5. .panelStyle{
6. background: lightblue ;
7. }
8.
9. .divStyle{
10. background: #eee ;
11. padding: 20px ;
12. margin: 20px ;
13. }
14.
15. .headerCaptionStyle{
16. background: #4B6978 ;
17. display: table-row ;
18. border: solid ;
19. text-align : center ;
20. width : 420px ;
21. height : 30px ;
22. padding-top : 3px ;
23. color : white ;
24. margin-left : 100px ;
25. display : block ;
26. }
27.
28. .headerStyle{
29. background: #4B6978 ;
30. display: table-row ;
31. border: solid ;
32. text-align : center ;
33. width : 100px ;
34. height : 30px ;
35. padding-top : 10px ;
©2017 C# CORNER.
SHARE THIS DOCUMENT AS IT IS. PLEASE DO NOT REPRODUCE, REPUBLISH, CHANGE OR COPY.
P a g e | 147
36. color : white ;
37. }
38.
39. .tableCaptionStyle{
40. background:#4B6978 ;
41. display: block ;
42. font-size : 20px ;
43. font-weight: bold ;
44. border: solid ;
45. text-align : center ;
46. width : 650px ;
47. height : 30px ;
48. padding-top : 3px ;
49. border-radius: 25px ;
50. margin-left : 30px ;
51. margin-top : 20px ;
52. color:white;
53. }
54.
55.
56. .rowCaptionStyle{
57. width : 600px ;
58. display : table-caption ;
59. background: #4B6978 ;
60. text-align : center ;
61. padding: 20px ;
62. font-size : 20px ;
63. font-weight : bold ;
64. color : white ;
65. }
66.
67. .rowStyle{
68. display : table-row ;
69. background: #eee ;
70. padding: 20px ;
71. margin: 20px ;
72. font-weight : bold ;
73. }
74.
75. .CellStyle{
76. display: table-cell ;
77. border: solid ;
78. border-color : white ;
79. text-align : center ;
©2017 C# CORNER.
SHARE THIS DOCUMENT AS IT IS. PLEASE DO NOT REPRODUCE, REPUBLISH, CHANGE OR COPY.
P a g e | 148
80. width : 100px ;
81. height : 30px ;
82. padding-top : 10px ;
83. }

ReactGetItems.tsx

This is the primary file where the logic and UI is written. ReactDOM.render method in the
ReactGetItemsWebPart file passes the control over to this file. Class ReactGetItems extends
React.Component and implements a constructor where the state objects are initialized. The
state object contains the list columns that will be populated using REST API calls.

1. public constructor(props: IReactGetItemsProps, state: IReactGetItemsState){


2. super(props);
3. this.state = {
4. items: [
5. {
6. "EmployeeName": "",
7. "EmployeeId": "",
8. "Experience":"",
9. "Location":""
10. }
11. ]
12. };
13. }

The class also contains componentDidMount method implementation which will be called after
mounting of the component. We can also make use of componentWillMount which is
synchronous in nature. We will make the REST API call within this method to retrieve the list
items and add it to the state object.

1. public componentDidMount(){
2. var reactHandler = this;
3. jquery.ajax({
4. url: `${this.props.siteurl}/_api/web/lists/getbytitle('EmployeeList')/items`,
5. type: "GET",
6. headers:{'Accept': 'application/json; odata=verbose;'},
7. success: function(resultData) {
8. reactHandler.setState({
9. items: resultData.d.results
10. });
11. },
12. error : function(jqXHR, textStatus, errorThrown) {
13. }
©2017 C# CORNER.
SHARE THIS DOCUMENT AS IT IS. PLEASE DO NOT REPRODUCE, REPUBLISH, CHANGE OR COPY.
P a g e | 149
14. });
15. }

Finally, the render method will read the state object and build the UI:

1. public render(): React.ReactElement<IReactGetItemsProps> {


2. return (
3.
4. <div className={styles.panelStyle} >
5. <br></br>
6.
7. <br></br>
8. <div className={styles.tableCaptionStyle} > Demo : Retrieve SharePoint List
Items using SPFx , REST API & React JS </div>
9. <br></br>
10. <div className={styles.headerCaptionStyle} > Employee Details</div>
11. <div className={styles.tableStyle} >
12.
13. <div className={styles.headerStyle} >
14. <div className={styles.CellStyle}>Employee Name</div>
15. <div className={styles.CellStyle}>Employee Id </div>
16. <div className={styles.CellStyle}>Experience</div>
17. <div className={styles.CellStyle}>Location</div>
18. </div>
19.
20. {this.state.items.map(function(item,key){
21.
22. return (<div className={styles.rowStyle} key={key}>
23. <div className={styles.CellStyle}>{item.EmployeeName}</div>
24. <div className={styles.CellStyle}>{item.EmployeeId}</div>
25. <div className={styles.CellStyle}>{item.Experience}</div>
26. <div className={styles.CellStyle}>{item.Location}</div>
27.
28. </div>);
29. })}
30. </div>
31. </div>
32. );
33. }

Test the Web Part in SharePoint Online

©2017 C# CORNER.
SHARE THIS DOCUMENT AS IT IS. PLEASE DO NOT REPRODUCE, REPUBLISH, CHANGE OR COPY.
P a g e | 150
Now let’s test the solution in SharePoint Online Workbench. Run gulp serve in the node
command and head over to the SharePoint Online Workbench URL by appending
“_layouts/15/workbench.aspx” to the URL.

The retrieved data has been displayed as a grid as shown below:

TSX File Contents for Retrieving List Items Using REST API and REACT
The tsx file content used to retrieve the list items via REST API is given below.

©2017 C# CORNER.
SHARE THIS DOCUMENT AS IT IS. PLEASE DO NOT REPRODUCE, REPUBLISH, CHANGE OR COPY.
P a g e | 151
1. import * as React from 'react';
2. import styles from './ReactGetItems.module.scss';
3. import { IReactGetItemsProps } from './IReactGetItemsProps';
4. import { escape } from '@microsoft/sp-lodash-subset';
5. import * as jquery from 'jquery';
6.
7. export interface IReactGetItemsState{
8. items:[
9. {
10. "EmployeeName": "",
11. "EmployeeId": "",
12. "Experience":"",
13. "Location":""
14. }]
15. }
16.
17. export default class ReactGetItems extends React.Component<IReactGetItemsProps,
IReactGetItemsState> {
18.
19. public constructor(props: IReactGetItemsProps, state: IReactGetItemsState){
20. super(props);
21. this.state = {
22. items: [
23. {
24. "EmployeeName": "",
25. "EmployeeId": "",
26. "Experience":"",
27. "Location":""
28. }
29. ]
30. };
31. }
32.
33. public componentDidMount(){
34. var reactHandler = this;
35. jquery.ajax({
36. url: `${this.props.siteurl}/_api/web/lists/getbytitle('EmployeeList')/items`,
37. type: "GET",
38. headers:{'Accept': 'application/json; odata=verbose;'},
39. success: function(resultData) {
40. reactHandler.setState({
41. items: resultData.d.results
42. });
43. },
©2017 C# CORNER.
SHARE THIS DOCUMENT AS IT IS. PLEASE DO NOT REPRODUCE, REPUBLISH, CHANGE OR COPY.
P a g e | 152
44. error : function(jqXHR, textStatus, errorThrown) {
45. }
46. });
47. }
48.
49.
50. public render(): React.ReactElement<IReactGetItemsProps> {
51. return (
52.
53. <div className={styles.panelStyle} >
54. <br></br>
55.
56. <br></br>
57. <div className={styles.tableCaptionStyle} > Demo : Retrieve SharePoint List
Items using SPFx , REST API & React JS </div>
58. <br></br>
59. <div className={styles.headerCaptionStyle} > Employee Details</div>
60. <div className={styles.tableStyle} >
61.
62. <div className={styles.headerStyle} >
63. <div className={styles.CellStyle}>Employee Name</div>
64. <div className={styles.CellStyle}>Employee Id </div>
65. <div className={styles.CellStyle}>Experience</div>
66. <div className={styles.CellStyle}>Location</div>
67.
68. </div>
69.
70. {this.state.items.map(function(item,key){
71.
72. return (<div className={styles.rowStyle} key={key}>
73. <div className={styles.CellStyle}>{item.EmployeeName}</div>
74. <div className={styles.CellStyle}>{item.EmployeeId}</div>
75. <div className={styles.CellStyle}>{item.Experience}</div>
76. <div className={styles.CellStyle}>{item.Location}</div>
77.
78. </div>);
79. })}
80.
81. </div>
82. </div>
83. );
84. }
85. }

©2017 C# CORNER.
SHARE THIS DOCUMENT AS IT IS. PLEASE DO NOT REPRODUCE, REPUBLISH, CHANGE OR COPY.
P a g e | 153
The major project files used in this solution have been zipped and uploaded at Microsoft
TechNet Gallery. Feel free to download them.

Summary

This book serves as a script cookbook to give you a head start with SharePoint Framework
development using TypeScript, PnP JS and React JS. More examples and scenario-based
solutions will be added to the upcoming versions as SharePoint Framework evolves with
respect to functionality. All the major solution files used in this book have been uploaded to
Microsoft TechNet gallery. Download them and use them as a reference while reading the book
so that you can get a better understanding of the structure and flow.

©2017 C# CORNER.
SHARE THIS DOCUMENT AS IT IS. PLEASE DO NOT REPRODUCE, REPUBLISH, CHANGE OR COPY.
P a g e | 154

You might also like