Introduction
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.
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.
- 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.
- import * as pnp from 'sp-pnp-js';
- let spweb = new pnp.Web("../");
- spweb.lists.get().then(function(){
- });
- public GetLists(): void{
- let spweb = new pnp.Web("../");
- spweb.lists.get().then(function(splists){
- splists.forEach(splist => {
- document.getElementById("listData").innerHTML += `<div>${splist.Title}</div>`;
- });
- });
- }
- public GetList(): void{
- let spweb = new pnp.Web("../");
- spweb.lists.getByTitle("TestList").get().then(function(splist){
- document.getElementById("listData").innerHTML += `
- <div>Title : ${splist.Title}</div>
- <div>Description: ${splist.Description}</div>
- <div>Template ID: ${splist.BaseTemplate}</div>
- `;
- });
- }
- public CreateList(): void{
- let spweb = new pnp.Web("../");
- let listTitle = "NewList";
- let listDescription = "List created using spfx + pnp";
- let listTemplateId = 100;
- let enableCT = false;
- spweb.lists.add(listTitle, listDescription,listTemplateId, enableCT).then(function(splist){
- document.getElementById("listData").innerHTML += `NewList Created`;
- });
- }
- public DeleteList(): void{
- let spweb = new pnp.Web("../");
- spweb.lists.getByTitle("NewList").delete().then(function(){
- document.getElementById("listData").innerHTML += `NewList deleted`;
- });
- }

Join the conversation! Your thoughts help the community grow.