SharePoint Folder Operations Demo Using PnP JS In React Based SPFx Webpart
In this article, we will learn how to perform operations like add, copy, move, and delete folders using the PnP library in the SPFx web part. PnPJs is an awesome library that providers wrappers around SharePoint REST API so that we as the developer do not have to write repetitive code and also worry about details on how to pass headers, data, etc. It is not only limited to SharePoint but we can also use it to call graph and office 365 API. As this library comes as an npm package, it can be used for any node js and javascript-based projects. Today we will use it in the context of the SharePoint Framework.
Let’s start by creating an SPFx web part. Go to the command prompt and directory where you want to create your SPFx solution.
md pnpfolderoperations cd pnpfolderoperations yo @microsoft/sharepoint
Use the below options to create a new SPFx solution. (we will be using React framework, just because it is really cool).
Once the solution is created you can open the project in your favorite editor(mine is VS code).
Now let’s install pnp library, use the below command in the node js command prompt.
npm install @pnp/sp
For the sake of simplicity, we won’t be using any fancy UI ..we will just create buttons and perform different operations on click of the buttons.
Let’s start making code changes, go-to editor.
Pass SharePoint Context to React component
1. Open src\webparts\foldersdemo\components\IFoldersdemoProps.ts
Create context properties to hold SharePoint context.
import { WebPartContext } from "@microsoft/sp-webpart-base"; export interface IFoldersdemoProps { description: string; context:WebPartContext }
2. Go to src\webparts\foldersdemo\FoldersdemoWebPart.ts
Click on Create Folders,
Let us see the results of Create Folders operation. It has created 4 folders.
Click on Rename Folder.
This will rename the folder as specified.
Click on Copy Folder.
The folder has been copied to the destination.
Click on the Move folder.
We can see the folder has been moved.
Conclusion
In this article, we have explored the below concepts.
- SPFx React-based web part
- Using PnPJS library in SPFx web part
- CRUD operations on folders in SharePoint using PnP JS