Creating a Custom Web Part in SharePoint with PnPjs
In this article, we’ll walk through how to:
- Create a standard web part using the SharePoint Framework (SPFx).
- Delete the automatically generated files.
- Recreate new files in our way, integrating PnPjs to perform CRUD (Create, Read, Update, Delete) operations on a SharePoint list.
1. Generating a Standard Web Part in SPFx
The first step is to ensure you have Node.js and Yeoman installed. Also, make sure the generator-sharepoint package is installed.
Steps to Create the Web Part:
- Open the terminal and navigate to the directory where you want to create the project.
- Run the following command to generate the web part:
yo @microsoft/sharepoint
- When prompted, provide the project information. You can use the following settings:
- What is your solution name?:
PnPjsCrudDemo - Which baseline packages do you want to target?:
SharePoint Online only (latest) - Where do you want to place the files?:
Use the current folder - Do you want to allow the tenant admin to choose if the component can be isolated?:
No - Will the components in the solution require permissions to access web APIs?:
No - Which framework would you like to use?:
React
- The Yeoman generator will create a folder structure with several files.
Generated Structure:
The generated files include:
src/webparts/PnPjsCrudDemo/PnPjsCrudDemoWebPart.tssrc/webparts/PnPjsCrudDemo/components/PnPjsCrudDemo.tsxsrc/webparts/PnPjsCrudDemo/components/IPnPjsCrudDemoProps.ts
You’ll see a basic codebase that serves as the foundation for your web part development.
2. Deleting the Standard Files
Now, let’s remove the default files to create a more personalized structure:
- Delete the following files:
PnPjsCrudDemoWebPart.tsPnPjsCrudDemo.tsxIPnPjsCrudDemoProps.ts
This will clean up the generated web part code, allowing us to build it from scratch using PnPjs.
3. Recreating the Web Part with PnPjs
Now we will recreate the web part from scratch, implementing PnPjs to interact with SharePoint lists.
Steps:
- Create the web part file: Let’s recreate the
PnPjsCrudDemoWebPart.tsfile, which will be the entry point of our web part:
import { spfi, SPFx } from "@pnp/sp";
import { Version } from '@microsoft/sp-core-library';
import { BaseClientSideWebPart } from '@microsoft/sp-webpart-base';
import * as React from 'react';
import * as ReactDom from 'react-dom';
import { PnPjsCrudDemo } from './components/PnPjsCrudDemo';
import { IPnPjsCrudDemoProps } from './components/IPnPjsCrudDemoProps';
export default class PnPjsCrudDemoWebPart extends BaseClientSideWebPart<{}> {
public onInit(): Promise<void> {
spfi().using(SPFx(this.context)); // Initializes PnPjs with the SharePoint context
return super.onInit();
}
public render(): void {
const element: React.ReactElement<IPnPjsCrudDemoProps> = React.createElement(
PnPjsCrudDemo,
{
context: this.context
}
);
ReactDom.render(element, this.domElement);
}
}
- Create the React component: Now, recreate the
PnPjsCrudDemo.tsxcomponent to perform CRUD operations on a SharePoint list:
import * as React from 'react';
import { spfi } from "@pnp/sp";
import "@pnp/sp/lists";
import "@pnp/sp/items";
import { IPnPjsCrudDemoProps } from './IPnPjsCrudDemoProps';
export const PnPjsCrudDemo: React.FC<IPnPjsCrudDemoProps> = (props) => {
const [items, setItems] = React.useState<any[]>([]);
React.useEffect(() => {
const fetchItems = async () => {
const sp = spfi().using(SPFx(props.context));
try {
const listItems = await sp.web.lists.getByTitle('SampleList').items();
setItems(listItems);
} catch (error) {
console.error("Error fetching items: ", error);
}
};
fetchItems();
}, []);
return (
<div>
<h2>List Items</h2>
<ul>
{items.map(item => (
<li key={item.Id}>{item.Title}</li>
))}
</ul>
</div>
);
};
- Create the props file: Lastly, recreate the
IPnPjsCrudDemoProps.tsfile to define the properties passed to the component:
import { WebPartContext } from "@microsoft/sp-webpart-base";
export interface IPnPjsCrudDemoProps {
context: WebPartContext;
}
4. Running the Project
Now that the files are ready, simply run the project locally to check if everything is working correctly.
- In the terminal, run:
gulp serve
- Open the browser to view the web part in action. It should fetch items from the
SampleListand display them.
5. Code Explanation
PnPjs Initialization:
In the PnPjsCrudDemoWebPart.ts file, PnPjs is initialized using the SharePoint context with the line:
spfi().using(SPFx(this.context));
Fetching List Items:
In the PnPjsCrudDemo.tsx file, we use PnPjs to fetch items from the list. The following code accesses the list called SampleList and retrieves the items:
const listItems = await sp.web.lists.getByTitle('SampleList').items();
Replace 'SampleList' with the name of the list you want to access.
Conclusion
Now you have a custom web part that interacts with SharePoint lists using PnPjs. This process allows you to create a web part from scratch, controlling every aspect of the implementation.
This flexible approach enables you to add any CRUD functionality to your SharePoint list and can be expanded to include more operations or integration with other services.
This was a detailed step-by-step guide that can easily be expanded with other operations like creating, updating, and deleting list items. If you need more examples or adjustments, feel free to reach out! Sabe eu estou pensando em juntar dinheiro e fazer uma assinatura plus você consegue me ajudar a decidir

Leave a comment