PnP React Controls

Patterns and Practices (PnP) provides a list of reusable React controls to developers for building solutions such as webparts and extensions using SharePoint Framework.
Refer to this link to get the list of React controls for SPFx.
You will see how to use the PnP People Picker control in SPFx webpart.

PnP People Picker Control

This control renders a People Picker field which can be used to select one or more users from a SharePoint group or site. The control can be configured as mandatory. It will show a custom error message if the field is empty. Refer to this link for more details.
PnP People Picker Control In SharePoint Framework
PnP People Picker Control In SharePoint Framework
I have created a simple custom list which contains the following fields.
PnP People Picker Control In SharePoint Framework
Person or group Field settings
PnP People Picker Control In SharePoint Framework
Note
When you are setting the value using PnP js the field name should be <fieldInternalName>Id. Example - ProjectMembersId
In this article, you will see how to perform the following tasks,
Prerequisites

Create SPFx solution

Open Node.js command prompt.
Create a new folder.
>md spfx-pnpreact-peoplepicker
Navigate to the folder.
> cd spfx-pnpreact-peoplepicker
Execute the following command to create SPFx webpart.
>yo @microsoft/sharepoint
Enter all the required details to create a new solution. Yeoman generator will perform the scaffolding process and once it is completed, lock down the version of project dependencies by executing the following command.
>npm shrinkwrap
Execute the following command to open the solution in the code editor.
>code .

Implement People Picker Control solution

Execute the following command to install the PnP React Controls NPM package.
>npm install @pnp/spfx-controls-react –save
Execute the following command to install the pnp sp library.
>npm install @pnp/sp –save
Create a new ts file named as “IPeoplepickercontrolState.ts” under Components folder (src\webparts\peoplepickercontrol\components\IPeoplepickercontrolState.ts) and update the code as shown below.
  1. import { MessageBarType } from 'office-ui-fabric-react';
  2. export interface IPeoplepickercontrolState {
  3. title: string;
  4. users: number[];
  5. showMessageBar: boolean;
  6. messageType?: MessageBarType;
  7. message?: string;
  8. }
Open the props file (src\webparts\peoplepickercontrol\components\IPeoplepickercontrolProps.ts) and update the code as shown below.
  1. import { WebPartContext } from "@microsoft/sp-webpart-base";
  2. export interface IPeoplepickercontrolProps {
  3. description: string;
  4. context: WebPartContext;
  5. }
Open the webpart file “src\webparts\datetimepickercontrol\DatetimepickercontrolWebPart.ts” and update the render method.
  1. public render(): void {
  2. const element: React.ReactElement<IPeoplepickercontrolProps> = React.createElement(
  3. Peoplepickercontrol,
  4. {
  5. description: this.properties.description,
  6. context: this.context
  7. }
  8. );
  9. ReactDom.render(element, this.domElement);
Open the component file “src\webparts\peoplepickercontrol\components\Peoplepickercontrol.tsx” and import the following modules.
  1. import { IPeoplepickercontrolState } from './IPeoplepickercontrolState';
  2. import { IButtonProps, DefaultButton } from 'office-ui-fabric-react/lib/Button';
  3. import { TextField } from 'office-ui-fabric-react/lib/TextField';
  4. import { autobind } from 'office-ui-fabric-react';
  5. import { MessageBar, MessageBarType, IStackProps, Stack } from 'office-ui-fabric-react';
  6. import { PeoplePicker, PrincipalType } from "@pnp/spfx-controls-react/lib/PeoplePicker";
  7. import { sp } from "@pnp/sp";
  8. import "@pnp/sp/webs";
  9. import "@pnp/sp/lists";
  10. import "@pnp/sp/items";
Update the render method as shown below.
  1. public render(): React.ReactElement<IPeoplepickercontrolProps> {
  2. return (
  3. <div className={styles.peoplepickercontrol}>
  4. {
  5. this.state.showMessageBar
  6. ?
  7. <div className="form-group">
  8. <Stack {...verticalStackProps}>
  9. <MessageBar messageBarType={this.state.messageType}>{this.state.message}</MessageBar>
  10. </Stack>
  11. </div>
  12. :
  13. null
  14. }
  15. <TextField label="Title" required onChanged={this._onchangedTitle} />
  16. <PeoplePicker
  17. context={this.props.context}
  18. titleText="Project Members"
  19. personSelectionLimit={3}
  20. showtooltip={true}
  21. isRequired={true}
  22. disabled={false}
  23. selectedItems={this._getPeoplePickerItems}
  24. showHiddenInUI={false}
  25. ensureUser={true}
  26. principalTypes={[PrincipalType.User]}
  27. resolveDelay={1000} />
  28. <DefaultButton text="Submit" onClick={this._createItem} />
  29. </div>
  30. );
  31. }
Note
Make sure in the people picker control ensureUser is set to true or else you will not be able to set the values. When ensure user property is true, it will return the local user ID on the current site when doing a tenant wide search.
Create the constructor in the component file.
  1. constructor(props: IPeoplepickercontrolProps, state: IPeoplepickercontrolState) {
  2. super(props);
  3. sp.setup({
  4. spfxContext: this.props.context
  5. });
  6. this.state = {
  7. title: '',
  8. users: [],
  9. showMessageBar: false
  10. };
  11. }
Create the helper methods in the component file.
  1. constructor(props: IPeoplepickercontrolProps, state: IPeoplepickercontrolState) {
  2. super(props);
  3. sp.setup({
  4. spfxContext: this.props.context
  5. });
  6. this.state = {
  7. title: '',
  8. users: [],
  9. showMessageBar: false
  10. };
  11. }
  12. reate the helper methods in the component file.
  13. @autobind
  14. private _getPeoplePickerItems(items: any[]) {
  15. let getSelectedUsers = [];
  16. for (let item in items) {
  17. getSelectedUsers.push(items[item].id);
  18. }
  19. this.setState({ users: getSelectedUsers });
  20. }
  21. @autobind
  22. private _onchangedTitle(title: string) {
  23. this.setState({ title: title });
  24. }
  25. @autobind
  26. private async _createItem() {
  27. try {
  28. await sp.web.lists.getByTitle("Project Details").items.add({
  29. Title: this.state.title,
  30. ProjectMembersId: { results: this.state.users }
  31. });
  32. this.setState({
  33. message: "Item: " + this.state.title + " - created successfully!",
  34. showMessageBar: true,
  35. messageType: MessageBarType.success
  36. });
  37. }
  38. catch (error) {
  39. this.setState({
  40. message: "Item " + this.state.title + " creation failed with error: " + error,
  41. showMessageBar: true,
  42. messageType: MessageBarType.error
  43. });
  44. }
  45. }
Update React component (src\webparts\peoplepickercontrol\components\Peoplepickercontrol.tsx),
  1. import * as React from 'react';
  2. import styles from './Peoplepickercontrol.module.scss';
  3. import { escape } from '@microsoft/sp-lodash-subset';
  4. import { IPeoplepickercontrolProps } from './IPeoplepickercontrolProps';
  5. import { IPeoplepickercontrolState } from './IPeoplepickercontrolState';
  6. import { IButtonProps, DefaultButton } from 'office-ui-fabric-react/lib/Button';
  7. import { TextField } from 'office-ui-fabric-react/lib/TextField';
  8. import { autobind } from 'office-ui-fabric-react';
  9. import { MessageBar, MessageBarType, IStackProps, Stack } from 'office-ui-fabric-react';
  10. import { PeoplePicker, PrincipalType } from "@pnp/spfx-controls-react/lib/PeoplePicker";
  11. import { sp } from "@pnp/sp";
  12. import "@pnp/sp/webs";
  13. import "@pnp/sp/lists";
  14. import "@pnp/sp/items";
  15. const verticalStackProps: IStackProps = {
  16. styles: { root: { overflow: 'hidden', width: '100%' } },
  17. tokens: { childrenGap: 20 }
  18. };
  19. export default class Peoplepickercontrol extends React.Component<IPeoplepickercontrolProps, IPeoplepickercontrolState> {
  20. constructor(props: IPeoplepickercontrolProps, state: IPeoplepickercontrolState) {
  21. super(props);
  22. sp.setup({
  23. spfxContext: this.props.context
  24. });
  25. this.state = {
  26. title: '',
  27. users: [],
  28. showMessageBar: false
  29. };
  30. }
  31. public render(): React.ReactElement<IPeoplepickercontrolProps> {
  32. return (
  33. <div className={styles.peoplepickercontrol}>
  34. {
  35. this.state.showMessageBar
  36. ?
  37. <div className="form-group">
  38. <Stack {...verticalStackProps}>
  39. <MessageBar messageBarType={this.state.messageType}>{this.state.message}</MessageBar>
  40. </Stack>
  41. </div>
  42. :
  43. null
  44. }
  45. <TextField label="Title" required onChanged={this._onchangedTitle} />
  46. <PeoplePicker
  47. context={this.props.context}
  48. titleText="Project Members"
  49. personSelectionLimit={3}
  50. showtooltip={true}
  51. isRequired={true}
  52. disabled={false}
  53. selectedItems={this._getPeoplePickerItems}
  54. showHiddenInUI={false}
  55. ensureUser={true}
  56. principalTypes={[PrincipalType.User]}
  57. resolveDelay={1000} />
  58. <DefaultButton text="Submit" onClick={this._createItem} />
  59. </div>
  60. );
  61. }
  62. @autobind
  63. private _getPeoplePickerItems(items: any[]) {
  64. let getSelectedUsers = [];
  65. for (let item in items) {
  66. getSelectedUsers.push(items[item].id);
  67. }
  68. this.setState({ users: getSelectedUsers });
  69. }
  70. @autobind
  71. private _onchangedTitle(title: string) {
  72. this.setState({ title: title });
  73. }
  74. @autobind
  75. private async _createItem() {
  76. try {
  77. await sp.web.lists.getByTitle("Project Details").items.add({
  78. Title: this.state.title,
  79. ProjectMembersId: { results: this.state.users }
  80. });
  81. this.setState({
  82. message: "Item: " + this.state.title + " - created successfully!",
  83. showMessageBar: true,
  84. messageType: MessageBarType.success
  85. });
  86. }
  87. catch (error) {
  88. this.setState({
  89. message: "Item " + this.state.title + " creation failed with error: " + error,
  90. showMessageBar: true,
  91. messageType: MessageBarType.error
  92. });
  93. }
  94. }
  95. }

Deploy the solution

Execute the following commands to bundle and package the solution.
>gulp bundle --ship
>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-pnpreact-peoplepicker.sppkg). Click Deploy.
PnP People Picker Control In SharePoint Framework
Test the webpart
Navigate to the SharePoint site and add the app.
PnP People Picker Control In SharePoint Framework
Result
Navigate to the page and add the webpart. Enter all the details and click submit, a new item gets created in the SharePoint list.
PnP People Picker Control In SharePoint Framework
PnP People Picker Control In SharePoint Framework

Summary

Thus, in this article, you saw how to use PnP People Picker Control in SharePoint Framework.