In the previous blog here, we looked at how to install apps on a SharePoint site. With SharePoint and Office Dev PnP CSOM, we could also add web parts to Modern Pages, both out of the box (OOB) web parts and custom web parts. For out of box web parts, refer to Chris O’Brien article here , where he has provided steps and also the web part IDs for the OOB webparts which is really helpful.
In this blog, we will look at steps to add a custom web part and set it properties.
For the below code, we will use OfficeDevPnP CSOM library. The high level steps for implementation are below:
1. Find the page where to add the web part. For creating a modern page programmatically, refer to this link here.
2. Find if the web part is added to the page, if not then add it using web part ID. We will read the web part ID from a JSON class where we have kept the details of the custom web part
3. After the web part is added, then set the web part properties using JSON schema of the properties using NewtonSoft.Json.
Note: If the web part app is just installed, then it might take time for the web part to be ready for use. Hence put a wait state till the web part is loaded for use.
The below code has the steps for adding the web part programmatically using CSOM
The above process could be used to add web part programmatically onto a page and set it’s properties.
Happy Coding !!