Read Modern SharePoint Page Metadata In SPFx WebPart Using PnP

In this article, you will learn how to read Modern SharePoint page metadata in SPFx WebPart using PnP.

Overview

 
SharePoint modern pages with page metadata provide more capabilities for end users to tag the content more appropriately. In certain development scenarios, we have to read these page properties in SPFx web part. SharePoint PnP (Pattern and Practices) provides simple APIs for reading page properties.
 
In this article, we will explore how to add page properties to the modern page and read it inside SPFx web part using PnP.
 

Add page properties to the modern page

 
Microsoft has provided an easy interface to handle page properties on the modern page, leaving behind the complexities with classic SharePoint of adding the fields to content type (which was not an easy option for the end users).
 
Follow the below steps to create a new page property on a modern page.
  1. Navigate to Pages library.
  2. Click “Add column” to add new columns to pages library.

    Read Modern SharePoint Page Metadata In SPFx WebPart Using PnP

  3. Add columns as below.

    Read Modern SharePoint Page Metadata In SPFx WebPart Using PnP

Set Individual Page Property Values

 
Now that we have defined custom properties, we will add values for those properties at the individual page level.
  1. Open a SharePoint page from Pages library.
  2. Click Edit.
  3. Click “Page details”.
  4. Specify values for our custom page properties.
  5. Click Republish. 
Read Modern SharePoint Page Metadata In SPFx WebPart Using PnP
 

SPFx Web Part to read page properties

 
Modern SharePoint offers an out of the box web part named "Page properties" to display the properties on a page. However, in a few scenarios, we have to read the page properties and process it further.
 
Open a command prompt. Create a directory for SPFx solution.
  1. md spfx-read-page-properties  
Navigate to the above-created directory.
  1. cd spfx-read-page-properties  
Run the Yeoman SharePoint Generator to create the solution.
  1. yo @microsoft/sharepoint  
Yeoman generator will present you with the wizard by asking questions about the solution to be created.
 
Read Modern SharePoint Page Metadata In SPFx WebPart Using PnP
 
Solution Name: Hit Enter to have default name (spfx-read-page-properties in this case) or type in any other name for your solution.
Selected choice: Hit enter
 
Target for the component: Here we can select the target environment where we are planning to deploy the client web part i.e. SharePoint Online or SharePoint On-Premises (SharePoint 2016 onwards).
Selected choice: SharePoint Online only (latest)
 
Place of files: We may choose to use the same folder or create a sub-folder for our solution.
Selected choice: Same folder
 
Deployment option: Selecting Y will allow the app to deployed instantly to all sites and will be accessible everywhere.
Selected choice: N (install on each site explicitly)
 
Permissions to access web APIs: Choose if the components in the solution require permissions to access web APIs that are unique and not shared with other components in the tenant.
Selected choice: N (solution contains unique permissions)
 
Type of client-side component to create: We can choose to create a client-side web part or an extension. Choose web part option.
Selected choice: WebPart
 
Web part name: Hit enter to select the default name or type in any other name.
Selected choice: PagePropertiesRead
 
Web part description: Hit enter to select the default description or type in any other value.
Selected choice: Read page properties using PnP
 
Framework to use: Select any JavaScript framework to develop the component. Available choices are (No JavaScript Framework, React, and Knockout)
Selected choice: React
 
Yeoman generator will perform a scaffolding process to generate the solution. The scaffolding process will take a significant amount of time.
 
Once the scaffolding process is completed, lock down the version of project dependencies by running below command.
  1. npm shrinkwrap  
In the command prompt type below command to open the solution in the code editor of your choice.
  1. code .  

NPM Packages Used

 
 
On the command prompt, run below command.
  1. npm i @pnp/logging @pnp/common @pnp/odata @pnp/sp --save  

Setup SP PnP for the Web Part

 
We will start by setting up the PnP to be used in our SPFx web part.
 
Open the web part file at src\webparts\pagePropertiesReader\PagePropertiesReaderWebPart.ts
 
Import PnP.
  1. // @pnp/sp imports    
  2. import { sp, Web } from '@pnp/sp';  
Implement OnInit method to setup PnP.
  1. public onInit(): Promise<void> {    
  2.   return super.onInit().then(_ => {    
  3.     sp.setup({    
  4.       spfxContext: this.context    
  5.     });    
  6.   });    
  7. }  

Pass Page Context from Web Part to React Component

 
React component cannot directly access the SharePoint context. It has to be passed from the web part to the React component.
 
Add pageContext property to React Props at src\webparts\pagePropertiesReader\components\IPagePropertiesReaderProps.ts
  1. import { PageContext } from '@microsoft/sp-page-context';  
  2.   
  3. export interface IPagePropertiesReaderProps {  
  4.   description: string;  
  5.   pageContext: PageContext;  
  6. }  
Set the pageConext inside render method of web part at src\webparts\pagePropertiesReader\PagePropertiesReaderWebPart.ts
  1. export default class PagePropertiesReaderWebPart extends BaseClientSideWebPart<IPagePropertiesReaderWebPartProps> {  
  2. .  
  3. .  
  4. .  
  5.   public render(): void {  
  6.     const element: React.ReactElement<IPagePropertiesReaderProps > = React.createElement(  
  7.       PagePropertiesReader,  
  8.       {  
  9.         description: this.properties.description,  
  10.         pageContext: this.context.pageContext  
  11.       }  
  12.     );  
  13.   
  14.     ReactDom.render(element, this.domElement);  
  15.   }  
  16. .  
  17. .  
  18. .  
  19. }  

Define the State

 
Let us define the state to store the custom page property values. Create a file named IPagePropertiesReaderState.ts at “src\webparts\pagePropertiesReader\components\”.
  1. export interface IPagePropertiesReaderState {  
  2.     department: string;  
  3.     freeText: string;  
  4. }  

Code the Web Part

 
Update the React component at “src\webparts\pagePropertiesReader\components\PagePropertiesReader.tsx” to read the page properties using PnP.
  1. import * as React from 'react';  
  2. import styles from './PagePropertiesReader.module.scss';  
  3. import { IPagePropertiesReaderProps } from './IPagePropertiesReaderProps';  
  4. import { IPagePropertiesReaderState } from './IPagePropertiesReaderState';  
  5. import { escape } from '@microsoft/sp-lodash-subset';  
  6.   
  7. // @pnp/sp imports    
  8. import { sp } from '@pnp/sp';  
  9.   
  10. export default class PagePropertiesReader extends React.Component<IPagePropertiesReaderProps, IPagePropertiesReaderState> {  
  11.   
  12.   constructor(props: IPagePropertiesReaderProps, state: IPagePropertiesReaderState) {  
  13.     super(props);  
  14.   
  15.     this.state = {  
  16.       department: "",  
  17.       freeText: ""  
  18.     };  
  19.   }  
  20.   
  21.   componentDidMount() {    
  22.     sp.web.lists.getById(this.props.pageContext.list.id.toString())  
  23.       .items.getById(this.props.pageContext.listItem.id)  
  24.         .select("Department,FreeText")  
  25.           .get()  
  26.             .then(d => {  
  27.               console.log(d);  
  28.               this.setState({  
  29.                 department: d.Department,  
  30.                 freeText: d.FreeText  
  31.               });  
  32.             });  
  33.   }  
  34.   
  35.   public render(): React.ReactElement<IPagePropertiesReaderProps> {  
  36.     return (  
  37.       <div className={ styles.pagePropertiesReader }>  
  38.         <div className={ styles.container }>  
  39.           <div className={ styles.row }>  
  40.             <div className={ styles.column }>  
  41.               <span className={ styles.title }>Welcome to SharePoint!</span>  
  42.               <p className={ styles.subTitle }>Page Properties</p>  
  43.               <p className={ styles.description }>Department: {escape(this.state.department)}</p>  
  44.               <p className={ styles.description }>FreeText: {escape(this.state.freeText)}</p>  
  45.             </div>  
  46.           </div>  
  47.         </div>  
  48.       </div>  
  49.     );  
  50.   }  
  51. }  

Test the web part

 
We will test the web part on a live SharePoint page, where we have set the custom property values.
  1. On the command prompt, type “gulp serve --nobrowser”.
  2. Open the SharePoint page with custom property values set. Append the below text to URL in the browser. 
    1. ?loadSPFX=true&debugManifestsFile=https://localhost:4321/temp/manifests.js   
  3. Click “Load debug scripts”, when prompted.
  4. Edit the page and add the web part (named PagePropertiesReader) to page.
  5. Verify the page property values getting displayed in our web part.

    Read Modern SharePoint Page Metadata In SPFx WebPart Using PnP

Summary

 
Page metadata provides more capabilities for end users to tag the content more appropriately in SharePoint. Modern SharePoint out of the box provides a web part named "Page properties". PnP provides simple APIs to read the custom page property values and process in SPFx web parts.