SharePoint Framework webpart with PnPJS CRUD operations

What is PNPJs?

PnPjs is a collection of libraries for we can use for consuming SharePoint, Graph, and Office 365 REST APIs in a safe way. We can use it within SharePoint Framework, Nodejs, or any JavaScript project. Moreover its an open source.

As a developer a bigger benefit I could see is the intellisense help in writing code. Even to perform simpler actions we may need to write too many lines of code instead we can use this PnPJS libraries and achieve with very few lines of code.

Step 1: Create basic SharePoint framework webpart:

Once the scaffolding process is completed we need lock down the version of the project dependencies by running this command

npm shrinkwrap

Run code . to open the created project in Visual studio code and check it’s a no JavaScript webpart. Yes, project structure does not have any react components in it.

Step 2: Install PnPJS libraries

Run the below code in command. You could see this includes multiple libraries like logging, common, odata, sp and graph. You can install whatever your need for your project. You can install one by one later as well when ever you require in your project. For now, I will install all.

npm install @pnp/logging @pnp/common @pnp/odata @pnp/sp @pnp/graph –save

Once that command completes, for a safer side please refresh the webpart solution and go to ‘package.json’ file to see whether it has the installed PnPJS libraries as in the below screen shot

We are ready now to start writing our PnPJS code do the CRUD actions in our SharePoint site. For this tutorial I will use a projects list in my SharePoint online site

Step 3: Add button UI and events to the webpart

First let us add this html div to add 4 buttons in our webpart

                <button class="${styles.button} create-Button">  
                <span class="${styles.label}">Create item</span>  
                <button class="${styles.button} read-Button">  
                <span class="${styles.label}">Read item</span>  
              </div>              <br>
              <button class="${styles.button} update-Button">  
                <span class="${styles.label}">Update item</span>  
                <button class="${styles.button} delete-Button">  
                <span class="${styles.label}">Delete item</span>  

Add the button event handler method

private setButtonsEventHandlers(): void {  
    const webPart: SpFxPnpJsCrudWebPart = this;  
    this.domElement.querySelector('button.create-Button').addEventListener('click', () => { webPart.createItem(); }); 
    this.domElement.querySelector('').addEventListener('click', () => { webPart.readItem(); });
    this.domElement.querySelector('button.update-Button').addEventListener('click', () => { webPart.updateItem(); });
    this.domElement.querySelector('button.delete-Button').addEventListener('click', () => { webPart.deleteItem(); });

Call the event handler method inside the render class


For now, we will create the empty methods for each button actions as below in the ‘SpFxPnpJsCrudWebPart.ts’

private createItem():void{    
  private readItem():void{    
  private updateItem():void{    
  private deleteItem():void{    

Finally the render class will look like this.

Let’s hit Gulp serve, to confirm how the button looks like. It’s here below.

Step 4: Add PnPJS code to create list item

In this step we will create an item in my ‘Projects’ list using PnPJS library.

We will use the code from pnpgithub site.

To get the pnp sp library method we need to first add this import code at top of the .ts file

import { sp, ItemAddResult } from "@pnp/sp";

Then add the below code into the ‘createItem’ method

// add an item to the list
      Title: "PnPJS",
      Technology: "Javascript",
      Resources: "6",
    }).then((iar: ItemAddResult) => {

We are ready with the create code, so let’s go with gulp serve and see the webpart in our SharePoint site workbench and click ‘create Item’. As I have not added code to display the result in webpart, I have just logged in the console. So will need to see the result in browser console window as below.

We could see the newly created item in my SharePoint list.

Step 5: Add PnPJS code to read list item

Replace the ‘readItem’ method with the below

private readItem():void{    
    // get a specific item by id
    sp.web.lists.getByTitle("Projects").items.getById(1).get().then((item: any) => {

Save the .ts file, refresh the SharePoint site workbench. Click ‘read item’ button. We could see the result in console window

Step 6: Add PnPJS code to update list item

private updateItem():void{   
    let list = sp.web.lists.getByTitle("Projects");
        Title: "My New Title - SPFx",
        Technology: "Updated - SharePoint"
    }).then(i => {

Our SharePoint list shows the updated list item

Step 7: Add PnPJS code to delete list item

private deleteItem():void{  
    let list = sp.web.lists.getByTitle("Projects");
    list.items.getById(1).delete().then(_ => {console.log('List Item Deleted')});  

Yes, the item is not available as our code deleted it

Thanks for reading my blog.