Here’s a detailed article explaining how to use sp-pnp-js with SharePoint Framework (SPFx) Web Parts based on the Microsoft documentation.
How to Use sp-pnp-js with SharePoint Framework (SPFx) Web Parts
The SharePoint Patterns and Practices (PnP) JavaScript library, commonly referred to as sp-pnp-js, is a powerful toolkit designed to simplify working with SharePoint REST APIs in JavaScript projects. It provides an abstraction layer that makes it easier to interact with SharePoint lists, libraries, users, and other resources. When building SharePoint Framework (SPFx) web parts, sp-pnp-js can be a valuable tool to streamline data access and improve development efficiency.
In this article, we’ll walk through how to integrate sp-pnp-js with SPFx web parts, explore its core functionalities, and provide best practices for working with this library in SharePoint development.
Why Use sp-pnp-js?
sp-pnp-js offers several benefits over directly using the SharePoint REST API:
- Simplified Syntax: It abstracts the complexity of REST queries, making the code cleaner and easier to maintain.
- Batch Requests: The library supports batching multiple requests, reducing the number of API calls and improving performance.
- TypeScript Support:
sp-pnp-jsis built with TypeScript, making it easier to integrate into SPFx projects that also use TypeScript.
Step-by-Step Guide to Using sp-pnp-js with SPFx Web Parts
1. Install the sp-pnp-js Library
To start using sp-pnp-js in your SPFx project, you first need to install the library as a dependency.
- Navigate to your SPFx project directory.
- Run the following command to install
@pnp/sp(the modern equivalent ofsp-pnp-js):
npm install @pnp/sp --save
This installs the PnP library in your SPFx project and saves it in the package.json as a dependency.
2. Import the Necessary Modules
Once installed, you can import the PnP library into your web part. Open your SPFx web part file (usually in the /src/webparts directory) and import the required modules from @pnp/sp. For example:
import { sp } from "@pnp/sp/presets/all";
This imports the entire PnP module, allowing you to access lists, libraries, and other SharePoint resources.
3. Initialize the PnP Context in Your Web Part
PnP needs to be initialized with the SharePoint context so that it can properly connect to the SharePoint site. You can do this in the onInit method of your web part class.
protected async onInit(): Promise<void> {
return super.onInit().then(_ => {
sp.setup({
spfxContext: this.context
});
});
}
This ensures that sp-pnp-js is set up correctly with the context of your current SPFx web part, allowing it to communicate with SharePoint.
4. Access SharePoint Data
Once sp-pnp-js is set up, you can easily access SharePoint data. For example, to retrieve items from a SharePoint list, you can use the following code:
sp.web.lists.getByTitle("YourListTitle").items.select("Title", "ID").get().then((items: any[]) => {
console.log(items);
});
In this example:
sp.web.lists.getByTitle("YourListTitle"): Gets a reference to the SharePoint list by its title..items.select("Title", "ID"): Selects the columns you want to retrieve (e.g.,TitleandID)..get(): Executes the query and returns the items.
You can also use more advanced query features such as filtering and ordering to refine the data retrieved from SharePoint.
5. Display the Data in Your Web Part
Once you have retrieved the SharePoint data using sp-pnp-js, you can display it in your web part by dynamically rendering the content. You can use basic DOM manipulation or React (if your web part uses React) to display the results.
For example, using plain TypeScript, you can dynamically insert the retrieved items into your web part:
this.domElement.innerHTML = `
<div>
<h3>List Items</h3>
<ul>
${items.map(item => `<li>${item.Title} (ID: ${item.ID})</li>`).join('')}
</ul>
</div>
`;
For React-based web parts, you can update the component’s state with the retrieved items and render them using JSX.
6. Perform CRUD Operations
sp-pnp-js supports create, read, update, and delete (CRUD) operations on SharePoint resources. Here’s how you can perform each operation using the PnP library:
- Create a New Item:
sp.web.lists.getByTitle("YourListTitle").items.add({
Title: "New Item Title"
}).then(response => {
console.log("Item added:", response);
});
- Update an Existing Item:
sp.web.lists.getByTitle("YourListTitle").items.getById(1).update({
Title: "Updated Item Title"
}).then(response => {
console.log("Item updated:", response);
});
- Delete an Item:
sp.web.lists.getByTitle("YourListTitle").items.getById(1).delete().then(response => {
console.log("Item deleted:", response);
});
These operations make it easy to manage SharePoint list items programmatically using sp-pnp-js.
7. Handle Errors
When working with SharePoint data, it’s important to handle errors that might occur, such as network issues or permission-related problems. You can use try-catch blocks to manage these errors effectively.
Here’s an example of error handling when fetching list items:
try {
const items = await sp.web.lists.getByTitle("YourListTitle").items.get();
console.log(items);
} catch (error) {
console.error("Error retrieving list items:", error);
}
This ensures that your web part doesn’t break when an error occurs and allows you to handle exceptions gracefully.
Best Practices for Using sp-pnp-js with SPFx
- Batch Requests: When making multiple API calls, use batching to improve performance. PnP supports batching, which allows multiple requests to be grouped into a single network call.
- Caching: Implement caching mechanisms where necessary to avoid repeated API calls for frequently accessed data.
- Error Handling: Always implement proper error handling, especially for operations that interact with SharePoint lists and libraries.
- Minimize Permissions: When deploying SPFx solutions, ensure that the necessary permissions are granted for the web part to perform actions on SharePoint data.
Summary of Key Steps and Commands
| Task | Command/Action |
|---|---|
Install sp-pnp-js | npm install @pnp/sp --save |
Import sp-pnp-js | import { sp } from "@pnp/sp/presets/all"; |
Setup PnP in onInit method | sp.setup({ spfxContext: this.context }); |
| Retrieve list items | sp.web.lists.getByTitle("YourListTitle").items.select(...).get(); |
| Create a new list item | sp.web.lists.getByTitle("YourListTitle").items.add({ Title: ... }); |
| Update a list item | sp.web.lists.getByTitle("YourListTitle").items.getById(id).update(); |
| Delete a list item | sp.web.lists.getByTitle("YourListTitle").items.getById(id).delete(); |
By following the steps in this guide, you can easily integrate sp-pnp-js with SPFx web parts, streamline SharePoint data access, and build robust, feature-rich web parts with minimal effort. The PnP library provides a more efficient and readable way to work with SharePoint REST APIs, enabling you to focus on building great user experiences in SharePoint.

Leave a comment