In Focus

PnP People Picker Control For SPFx

In this article, you will learn about PnP People Picker Control for SPFx.

Overview

 
PnP has provided a control that renders as a People Picker field, which can be used to select one or more users from a SharePoint site or group. This control is useful to be used in SPFx web part to get the people information from the users. People Picker control offers various configuration options to support most business needs.
 
In  this article, we will explore the People Picker control from PnP on how to use and configure it in SPFx web part. We will develop a practical scenario to capture the people information in SPFx web part using PnP People Picker Control and store it in SharePoint list.
 

Develop SharePoint Framework Web Part

 
Open a command prompt. Create a directory for SPFx solution.
  1. md spfx-pnp-people-picker  
Navigate to the above-created directory.
  1. cd spfx-pnp-people-picker  
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.
 
PnP People Picker Control For SPFx
 
Solution Name: Hit Enter to have default name (spfx-pnp-people-picker 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 OnPremise (SharePoint 2016 onwards).
Selected choice: SharePoint Online only (latest)
 
Place of files: We may choose to use the same folder or create a subfolder 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: PnPPeoplePicker
 
Web part description: Hit Enter to select the default description or type in any other value.
Selected choice: Use PnP People Picker control in SPFx solution
 
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

 
@pnp/spfx-controls-react (https://sharepoint.github.io/sp-dev-fx-controls-react/)
On the command prompt, run below command to include the npm package.
  1. npm install @pnp/spfx-controls-react --save  
@pnp/sp (https://www.npmjs.com/package/@pnp/sp)
On the command prompt, run below command.
  1. npm i @pnp/logging @pnp/common @pnp/odata @pnp/sp --save  

Pass the context from web part to React Component

 
As we need the SharePoint context to work with People Picker, we will have to pass it from our web part to the React component.
 
Open React component properties at “src\webparts\pnPPeoplePicker\components\IPnPPeoplePickerProps.ts” and add below properties.
  1. import { WebPartContext } from '@microsoft/sp-webpart-base';  
  2.   
  3. export interface IPnPPeoplePickerProps {  
  4.   description: string;  
  5.   context: WebPartContext;  
  6. }  
From our web part (src\webparts\pnPPeoplePicker\PnPPeoplePickerWebPart.ts), pass the context to React component.
  1. export default class PnPPeoplePickerWebPart extends BaseClientSideWebPart<IPnPPeoplePickerWebPartProps> {  
  2.   
  3.   public render(): void {  
  4.     const element: React.ReactElement<IPnPPeoplePickerProps > = React.createElement(  
  5.       PnPPeoplePicker,  
  6.       {  
  7.         description: this.properties.description,  
  8.         context: this.context  
  9.       }  
  10.     );  
  11.   
  12.     ReactDom.render(element, this.domElement);  
  13.   }  
  14.      .  
  15.      .  
  16.      .  
  17. }  

Code the Web Part

 
On the command prompt, type the below command to open the solution in the code editor of your choice.
  1. code .  
Open the React component file at “src\webparts\pnPPeoplePicker\components\PnPPeoplePicker.tsx”.
 
Add below imports.
  1. import { PeoplePicker, PrincipalType } from "@pnp/spfx-controls-react/lib/PeoplePicker";  
Use the PeoplePicker control in the render method as follows.
  1. export default class PnPPeoplePicker extends React.Component<IPnPPeoplePickerProps, {}> {    
  2.   public render(): React.ReactElement<IPnPPeoplePickerProps> {    
  3.     return (    
  4.       <div className={ styles.pnPPeoplePicker }>    
  5.         <div className={ styles.container }>    
  6.           <div className={ styles.row }>    
  7.             <div className={ styles.column }>    
  8.               <span className={ styles.title }>Welcome to SharePoint!</span>    
  9.               <p className={ styles.subTitle }>Customize SharePoint experiences using Web Parts.</p>    
  10.                   
  11.               <PeoplePicker    
  12.                 context={this.props.context}    
  13.                 titleText="People Picker"    
  14.                 personSelectionLimit={3}    
  15.                 groupName={""// Leave this blank in case you want to filter from all users    
  16.                 showtooltip={true}    
  17.                 isRequired={true}    
  18.                 disabled={false}    
  19.                 ensureUser={true}    
  20.                 selectedItems={this._getPeoplePickerItems}    
  21.                 showHiddenInUI={false}    
  22.                 principalTypes={[PrincipalType.User]}    
  23.                 resolveDelay={1000} />        
  24.             </div>    
  25.           </div>    
  26.         </div>    
  27.       </div>    
  28.     );    
  29.   }    
  30. }    
In the PeoplePicker component, set "ensure user property" to true. It will return the local user ID on the current site.
 
Implement selectedItems property to get the selected People from the PeoplePicker.
  1. private _getPeoplePickerItems(items: any[]) {  
  2.   console.log('Items:', items);  
  3. }  

Define the State

 
Let us define the state to store the selected user ids.
 
Add file IPnPPeoplePickerState.ts under folder “\src\webparts\pnPPeoplePicker\components\”.
  1. export interface IPnPPeoplePickerState {  
  2.     addUsers: string[];  
  3. }  
Update the React component “\src\webparts\pnPPeoplePicker\components\PnPPeoplePicker.tsx” to use the state.
  1. import * as React from 'react';    
  2. import styles from './PnPPeoplePicker.module.scss';    
  3. import { IPnPPeoplePickerProps } from './IPnPPeoplePickerProps';    
  4. import { IPnPPeoplePickerState } from './IPnPPeoplePickerState';    
  5.     
  6. // @pnp/sp imports      
  7. import { sp, Web } from '@pnp/sp';    
  8.     
  9. import { PeoplePicker, PrincipalType } from "@pnp/spfx-controls-react/lib/PeoplePicker";    
  10.     
  11. export default class PnPPeoplePicker extends React.Component<IPnPPeoplePickerProps, IPnPPeoplePickerState> {      
  12.     
  13.   constructor(props: IPnPPeoplePickerProps, state: IPnPPeoplePickerState) {    
  14.     super(props);    
  15.     
  16.     this.state = {    
  17.       addUsers: []    
  18.     };    
  19.   }    
  20.    .    
  21.    .    
  22.    .    
  23. }  

Define the controls

 
Let us add a button control. On click of the button, we will add the selected users from People Picker to the SharePoint list.
 
Open React component PnPPeoplePicker.tsx at folder “src\webparts\pnPPeoplePicker\components\”.
 
Add the below import for button control.
  1. // Import button component      
  2. import { IButtonProps, DefaultButton } from 'office-ui-fabric-react/lib/Button';   
  3.   
  4. import { autobind } from 'office-ui-fabric-react';  
Define a button inside the render method.
  1. <DefaultButton    
  2.   data-automation-id="addSelectedUsers"    
  3.   title="Add Selected Users"    
  4.   onClick={this.addSelectedUsers}>    
  5.   Add Selected Users    
  6. </DefaultButton>   
Implement the supporting methods as below.
  1. @autobind   
  2. private addSelectedUsers(): void {    
  3.   sp.web.lists.getByTitle("SPFx Users").items.add({  
  4.     Title: getGUID(),  
  5.     Users: {   
  6.         results: this.state.addUsers  
  7.     }  
  8.   }).then(i => {  
  9.       console.log(i);  
  10.   });  
  11. }   

Add Selected Users to SharePoint list

 
We are adding the selected users to React component state using the addSelectedUsers method of PeoplePicker PnP control. Now, we will implement a logic to add the selected users from React state to actual SharePoint list.
 
Add the below imports.
  1. // @pnp/sp imports    
  2. import { sp } from '@pnp/sp';    
  3. import { getGUID } from "@pnp/common";  
  4.   
  5. // Import button component      
  6. import { DefaultButton } from 'office-ui-fabric-react/lib/Button';   
  7. import { autobind } from 'office-ui-fabric-react';   
Add button insider Render method.
  1. <DefaultButton    
  2.   data-automation-id="addSelectedUsers"    
  3.   title="Add Selected Users"    
  4.   onClick={this.addSelectedUsers}>    
  5.   Add Selected Users    
  6. </DefaultButton>    
Implement addSelectedUsers method.
  1. @autobind   
  2. private addSelectedUsers(): void {    
  3.   sp.web.lists.getByTitle("SPFx Users").items.add({  
  4.     Title: getGUID(),  
  5.     Users: {   
  6.         results: this.state.addUsers  
  7.     }  
  8.   }).then(i => {  
  9.       console.log(i);  
  10.   });  
  11. }   

Setup SharePoint List

 
Setup SharePoint list (named “SPFx Users”) with below schema.
 
Column Type Comments
Title Single line of text Out of box title column
Users Person or Group Set “Allow multiple selections” to Yes
 

Test the PnP People Picker

  1. On the command prompt, type “gulp serve”
  2. Open SharePoint site.
  3.  Navigate to /_layouts/15/workbench.aspx
  4.  Locate and add the webpart (named PnPPeoplePicker) to page.
  5. Type in the user names in the people picker.
  6. Click “Add Selected Users”.

    PnP People Picker Control For SPFx
  7. The selected users should get added to the SharePoint list.

    PnP People Picker Control For SPFx

Summary

 
In this article, we explored the practical use of People Picker control in SPFx web part. We configured the PnP People Picker control to capture the information from the user and used PnP list item operation to add the information to SharePoint list.