Create List Item Using PnP JS In SharePoint Framework

In this blog, you will see how to create list item using PnP JS in SharePoint Framework.
 

@pnp/sp

 
This package contains the fluent api used to call the SharePoint rest services. Refer to this link for more details.
 

Create List Item

 
 
 
 
 

Create SPFx solution

 
Open Node.js command prompt.
 
Create a new folder.
  1. >md spfx-pnpjs-createitem  
Navigate to the folder.
  1. >cd spfx-pnpjs-createitem  
Execute the following command to create SPFx webpart.
  1. >yo @microsoft/sharepoint  
Enter all the required details to create a new solution. Enter the webpart named CreateItem and select React framework.
 
Yeoman generator will perform scaffolding process and once it is completed, lock down the version of project dependencies by executing the following command.
  1. >npm shrinkwrap  
Execute the following command to open the solution in the code editor.
  1. >code .  
Execute the following command to install the pnp sp library.
  1. >npm install @pnp/sp --save  
Create a new file named as “ICreateItemState.ts” under Components folder and update the code as shown below.
  1. import { MessageBarType } from 'office-ui-fabric-react';  
  2.   
  3. export interface ICreateItemState {  
  4.     title: string;  
  5.     showMessageBar: boolean;    
  6.     messageType?: MessageBarType;    
  7.     message?: string;  
  8. }  
Open the component file “src\webparts\createItem\components\CreateItem.tsx” and update the code as shown below.
  1. import * as React from 'react';  
  2. import styles from './CreateItem.module.scss';  
  3. import { ICreateItemProps } from './ICreateItemProps';  
  4. import { ICreateItemState } from './ICreateItemState';  
  5. import { escape } from '@microsoft/sp-lodash-subset';  
  6. import { TextField } from 'office-ui-fabric-react/lib/TextField';  
  7. import { MessageBar, MessageBarType, IStackProps, Stack } from 'office-ui-fabric-react';  
  8. import { autobind } from 'office-ui-fabric-react';  
  9. import { sp } from "@pnp/sp";  
  10. import "@pnp/sp/webs";  
  11. import "@pnp/sp/lists";  
  12. import "@pnp/sp/items";  
  13.   
  14. const verticalStackProps: IStackProps = {  
  15.   styles: { root: { overflow: 'hidden', width: '100%' } },  
  16.   tokens: { childrenGap: 20 }  
  17. };  
  18.   
  19. export default class CreateItem extends React.Component<ICreateItemProps, ICreateItemState> {  
  20.   constructor(props: ICreateItemProps, state: ICreateItemState) {  
  21.     super(props);  
  22.     this.state = {  
  23.       title: '',  
  24.       showMessageBar: false  
  25.     };  
  26.   }  
  27.   public render(): React.ReactElement<ICreateItemProps> {  
  28.     return (  
  29.       <div className={styles.container}>  
  30.         <div className={styles.row}>  
  31.           {  
  32.             this.state.showMessageBar  
  33.               ?  
  34.               <div className="form-group">  
  35.                 <Stack {...verticalStackProps}>  
  36.                   <MessageBar messageBarType={this.state.messageType}>{this.state.message}</MessageBar>  
  37.                 </Stack>  
  38.               </div>  
  39.               :  
  40.               null  
  41.           }  
  42.           <div className={styles.row}>  
  43.             <div className="form-group">  
  44.               <TextField label="Title" required onChanged={this.onchangedTitle} />  
  45.             </div>  
  46.             <div className={`${styles.buttonRow} form-group`}>  
  47.               <button type="button" className="btn btn-primary" onClick={this.createItem}>Submit</button>  
  48.             </div>  
  49.           </div>  
  50.         </div>  
  51.       </div>  
  52.     );  
  53.   }  
  54.   
  55.   @autobind  
  56.   private onchangedTitle(title: any): void {  
  57.     this.setState({ title: title });  
  58.   }  
  59.   
  60.   @autobind  
  61.   private async createItem() {  
  62.     try {  
  63.       await sp.web.lists.getByTitle('Customer Tracking').items.add({  
  64.         Title: this.state.title  
  65.       });  
  66.       this.setState({  
  67.         message: "Item: " + this.state.title + " - created successfully!",  
  68.         showMessageBar: true,  
  69.         messageType: MessageBarType.success  
  70.       });  
  71.     }  
  72.     catch (error) {  
  73.       this.setState({  
  74.         message: "Item " + this.state.title + " creation failed with error: " + error,  
  75.         showMessageBar: true,  
  76.         messageType: MessageBarType.error  
  77.       });  
  78.     }  
  79.   }  
  80. }  
Open the webpart file “src\webparts\createItem\CreateItemWebPart.ts” and add the OnInit() method.
  1. public onInit(): Promise<void> {  
  2.   return super.onInit().then(_ => {    
  3.     sp.setup({  
  4.       spfxContext: this.context  
  5.     });  
  6.   });  
  7. }   

Deploy the solution

 
Execute the following commands to bundle and package the solution.
  1. >gulp bundle --ship  
  2. >gulp package-solution --ship  
Navigate to tenant app catalog – Example: https://c986.sharepoint.com/sites/appcatalog/SitePages/Home.aspx
 
Go to Apps for SharePoint library and upload the package file (sharepoint\solution\spfx-pnpjs-createitem.sppkg). Click Deploy.
 

Test the webpart

 
Navigate to the SharePoint site and add the app. Navigate to the page and add the webpart.
 
Result
 
 
 

Summary

 
Thus, in this blog, you saw how to create list items using PnP JS in SharePoint Framework.