Developing SharePoint Framework Web Parts Using PnP JavaScript Modules


In this article, you will learn how to work with SharePoint list operations on SharePoint framework Web parts, using PnP JavaScript libraries.

This article shows how to import PnP JavaScript libraries into SPFx Web part and also shows the samples of SharePoint list operations , using PnP code with the screenshots. 

Create SPFx Web part

SharePoint framework Web part needs to be created. In this sample, plain Web part is created without any frameworks.

In the previous articles, you can learn about developing SharePoint Framework Web parts.  

Installing PnP JavaScript modules

To develop the Web parts, using PnP modules, PnP JavaScript module needs to be installed/ imported into the SPFx project. The same can be accomplished, using NPM command. Open the command prompt and navigate to the project (created above) folder. The code snippet given below shows NPM command to install PnP JavaScript modules to the project.

  1. npm install --save sp-pnp-js   

SharePoint operations

The installed modules will be present under the node_modules folder of the project. The modules can be imported to the Webparts, using import command.

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

Similarly, other objects can be imported. First, the required Web object is created, using the site relative URL. With the created object, lists property is accessed and the operations are performed on the lists collection property.

  1. let spweb = new pnp.Web("../");  

  2. spweb.lists.get().then(function(){  }

  3. );  

Get Lists Let us see how to retrieve all the lists available on SharePoint site. The Web object is created, using the relative URL. Subsequently, the lists object is retrieved, using the code snippet given below.

  1. public GetLists(): void{    

  2. let spweb = new pnp.Web("../");    

  3. spweb.lists.get().then(function(splists){      

  4. splists.forEach(splist => {        

  5. document.getElementById("listData").innerHTML += `<div>${splist.Title}</div>`;