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. export interface ICreateItemState {
  3. title: string;
  4. showMessageBar: boolean;
  5. messageType?: MessageBarType;
  6. message?: string;
  7. }
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. const verticalStackProps: IStackProps = {
  14. styles: { root: { overflow: 'hidden', width: '100%' } },
  15. tokens: { childrenGap: 20 }
  16. };
  17. export default class CreateItem extends React.Component<ICreateItemProps, ICreateItemState> {
  18. constructor(props: ICreateItemProps, state: ICreateItemState) {
  19. super(props);
  20. this.state = {
  21. title: '',
  22. showMessageBar: false
  23. };
  24. }
  25. public render(): React.ReactElement<ICreateItemProps> {
  26. return (
  27. <div className={styles.container}>
  28. <div className={styles.row}>
  29. {
  30. this.state.showMessageBar
  31. ?
  32. <div className="form-group">
  33. <Stack {...verticalStackProps}>
  34. <MessageBar messageBarType={this.state.messageType}>{this.state.message}</MessageBar>
  35. </Stack>
  36. </div>
  37. :
  38. null
  39. }
  40. <div className={styles.row}>
  41. <div className="form-group">
  42. <TextField label="Title" required onChanged={this.onchangedTitle} />
  43. </div>
  44. <div className={`${styles.buttonRow} form-group`}>
  45. <button type="button" className="btn btn-primary" onClick={this.createItem}>Submit</button>
  46. </div>
  47. </div>
  48. </div>
  49. </div>
  50. );
  51. }
  52. @autobind
  53. private onchangedTitle(title: any): void {
  54. this.setState({ title: title });
  55. }
  56. @autobind
  57. private async createItem() {
  58. try {
  59. await sp.web.lists.getByTitle('Customer Tracking').items.add({
  60. Title: this.state.title
  61. });
  62. this.setState({
  63. message: "Item: " + this.state.title + " - created successfully!",
  64. showMessageBar: true,
  65. messageType: MessageBarType.success
  66. });
  67. }
  68. catch (error) {
  69. this.setState({
  70. message: "Item " + this.state.title + " creation failed with error: " + error,
  71. showMessageBar: true,
  72. messageType: MessageBarType.error
  73. });
  74. }
  75. }
  76. }
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.