Modern Page Provisioning in the SharePoint Framework (SPFx)

This article provides steps to implement the mordern page provisioning using PnPjs in the SharePoint Framework (SPFx), generally PnPjs clientside pages module allows you to created, edit, and delete modern SharePoint pages. There are methods to update the page settings and add/remove client-side webparts.

Create a new web part project

Open power shell and run following comment to create a new web part by running the Yeoman SharePoint Generator

yo @microsoft/sharepoint

When prompted:

Enter the webpart name as your solution name, and then select Enter.
Select Create a subfolder with solution name for where to place the files.
Select Y to allow the solution to be deployed to all sites immediately.
Select N on the question if solution contains unique permissions.
Select WebPart as the client-side component type to be created.

The next set of prompts ask for specific information about your web part:

Enter your web part name, and then select Enter.
Enter your web part description, and then select Enter.
Select React framework as the framework you would like to use, and then select Enter.

Start Visual Studio Code (or your favorite code editor) within the context of the newly created project folder.

cd .\web part name\
code .

Install the library and required dependencies

npm install @pnp/sp --save

Import the library into your application, update constructor, and access the root sp object in render for PnPjs libraries.

sp.setup({spfxContext: this.props.spcontect});

Configure the custom properties

Create a new source code file under the src\webparts\<Webpart name>\components\ folder of the solution. Create the new file I<web part name>State.ts and use it to create a TypeScript Interface

export interface ISpfxPnpPageprovisioningState {
  title: string;
  name:string;
}

In addition, you need to update the render method of the client-side web part to create a properly configured instance of the React component for rendering. The following code shows the updated method definition.

  public render(): void {
    const element: React.ReactElement<ISpfxPnpPageprovisioningProps> = React.createElement(
      SpfxPnpPageprovisioning,
      {
        description: this.properties.description,
        context:this.context
      }
    );
    ReactDom.render(element, this.domElement);
  }

Update the tsx file located under the components. First, add some import statements to import the types you defined earlier. Notice the import for I<web part name>Props and I<web part name>State. There are also some imports pnp sp imports.

import * as React from 'react';
import styles from './SpfxPnpPageprovisioning.module.scss';
import { ISpfxPnpPageprovisioningProps } from './ISpfxPnpPageprovisioningProps';
import { ISpfxPnpPageprovisioningState } from './ISpfxPnpPageprovisioningState';
import { autobind } from 'office-ui-fabric-react/lib/Utilities';
import { sp } from "@pnp/sp";
import "@pnp/sp/webs";
import "@pnp/sp/clientside-pages/web";
import { PrimaryButton, TextField } from 'office-ui-fabric-react';
import { ClientsideText, ClientsideWebpart } from "@pnp/sp/clientside-pages";
import "@pnp/sp/comments/clientside-page";

Replace this render function with the following code.

  public render(): React.ReactElement<ISpfxPnpPageprovisioningProps> {
    return (
      <div className={styles.spfxPnpPageprovisioning}>
        <TextField label="Page Name" onChanged={(val) => { this.setState({ name: val }) }} />
        <TextField label="Page Title" onChanged={(val) => { this.setState({ title: val }) }} />
        <br />
        <PrimaryButton text="Create Page" onClick={this._CreatePage} />
      </div>
    );
  }

Update the React component type declaration and add a constructor, as shown in the following example.

export default class SpfxPnpPageprovisioning extends React.Component<ISpfxPnpPageprovisioningProps, ISpfxPnpPageprovisioningState> {
  constructor(props: ISpfxPnpPageprovisioningProps) {
    super(props);
    sp.setup({
      spfxContext: this.props.context
    });
    this.state = {
      title: '',
      name: ''
    }
  }

place the below code inside the react component code, these function using PnPjs to create modern page in the Site Pages library

@autobind
  private async _CreatePage() {
    //Page layout type are "Article" | "Home"
    const page = await sp.web.addClientsidePage(this.state.name, this.state.title, "Article");
    let section = page.addSection()
    //Column size factor. Max value is 12 (= one column), other options are 8,6,4 or 0
    let column1 = section.addColumn(8);
    let column2 = section.addColumn(4);

    column1.addControl(new ClientsideText("This is text added into column 1"))
    column2.addControl(new ClientsideText("This is text added into column 2"))

    const partDefs = await sp.web.getClientsideWebParts();
    const partDef = partDefs.filter(c => c.Id === "490d7c76-1824-45b2-9de3-676421c997fa");
    const part = ClientsideWebpart.fromComponentDef(partDef[0]);
    column1.addControl(part);
    await page.save();
    // //Header
    // page.topicHeader = "My cool header!";
    // page.headerTextAlignment = "Center";

    // //You can manage to show and hide the published date
    // page.showPublishDate = true;

    // //can hide/show the comments
    // await page.enableComments();
    // //Banner image can change like this
    // page.bannerImageUrl = "/server/relative/path/to/image.png";
  }

Deploy the solution

You’re now ready to build, bundle, package, and deploy the solution.

Run the gulp commands to verify that the solution builds correctly.

gulp build

Use the following command to bundle and package the solution.

gulp bundle --ship
gulp package-solution --ship

Browse to the app catalog of your target tenant and upload the solution package. You can find the solution package under the sharepoint/solution folder of your solution. It is the .sppkg file. After you upload the solution package in the app catalog. you can find and the web part anywhere across the tenant.

Sharing is caring!

If you have any questions, feel free to let me know in the comments section.
Happy coding!!!

10 thoughts on “Modern Page Provisioning in the SharePoint Framework (SPFx)

  1. Bruno August 31, 2020 / 10:02 pm

    Hi, how about adding a new page using the template created by me using a SharePointFullPage webpart? I dont want my customers to have to create them from native UI…

    Liked by 1 person

      • Bruno September 1, 2020 / 8:36 pm

        Hi, but when we specify the parameter for the template (in your case “Article”), is it possible to use a template created by me and deployed as a SharePointFullPage webpart?

        Liked by 1 person

      • Ravichandran Krishnasamy September 2, 2020 / 1:45 pm

        Hi Bruno,

        When I tried the same I got error, But instead of using template if you use page as template all works perfect.

        Liked by 1 person

  2. Bruno October 9, 2020 / 2:51 pm

    I was able to do that by using this:
    await sp.web.addClientsidePage(url, title, “SingleWebPartAppPage”).then(async page => {
    let sec = page.addSection();
    sec.addColumn(12);

    await sp.web.getClientsideWebParts().then(partDefs => {
    const partDef = partDefs.filter(c => c.Id.replace(“{“,””).replace(“}”,””).toLowerCase() === templateId);
    if (partDef.length < 1) {
    throw new Error("Could not find the web part");
    } else {
    const part = ClientsideWebpart.fromComponentDef(partDef[0]);
    sec.addControl(part);
    }
    });

    await page.save(false);
    });

    Liked by 1 person

  3. Abish Kumar June 4, 2021 / 12:16 pm

    How can we create a page with in the folders?

    Like

    • Ravichandran Krishnasamy June 6, 2021 / 10:54 am

      Hi Abish,

      You can this for create new page
      const page = await sp.web.addClientSidePageByPath(`file-name`, “/sites/dev/SitePages”);

      use this for edit existing page
      const page = await ClientSidePage.fromFile(sp.web.getFileByServerRelativeUrl(“/sites/dev/SitePages/ExistingFile.aspx”));

      Like

  4. Abish Kumar June 7, 2021 / 5:50 am

    addClientSidePageByPath method is not supporting for v2.4.0. My current version is 2.4.0. What should i do now?

    Like

  5. Abish Kumar June 8, 2021 / 4:47 pm

    Hi Sir,

    I have created the page with file viewer web part. All file format is working fine. But excel and csv file is not loading. Please help me out.

    Like

Comments

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google photo

You are commenting using your Google account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s