PnP Taxonomy Picker Control For SPFx

Overview

 
PnP has provided a Taxonomy picker control which can be used to select one or more terms from a TermSet by its name or ID. This control is useful to be used in SPFx web part to allow users for managed metadata selection. Taxonomy Picker control offers various configuration options to support most of the business needs.
 
During this article, we will explore the Taxonomy Picker control from PnP on how to use, and configure it in SPFx web part. We will develop a practical scenario to capture the managed metadata information in SPFx web part using PnP Taxonomy 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-taxonomy-picker  
Navigate to the above-created directory.
  1. cd spfx-pnp- taxonomy-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 Taxonomy Picker Control For SPFx 
 
Solution Name: Hit Enter to have default name (spfx-pnp-taxonomy-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 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: PnPTaxonomyPicker
 
Web part description: Hit Enter to select the default description or type in any other value.
Selected choice: Use PnP Taxonomy 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

 
On the command prompt, run below command to include the npm package.
  1. npm install @pnp/spfx-controls-react --save  
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 Taxonomy picker, we will have to pass it from our web part to the React component.
 
On the command prompt, type the below command to open the solution in the code editor of your choice.
  1. code .  
Open React component properties at “src\webparts\pnPTaxonomyPicker\components\IPnPTaxonomyPickerProps.ts”
Add below properties.
  1. import { WebPartContext } from '@microsoft/sp-webpart-base';  
  2.   
  3. export interface IPnPTaxonomyPickerProps {  
  4.   description: string;  
  5.   context: WebPartContext;  
  6. }  
From our web part (src\webparts\pnPTaxonomyPicker\PnPTaxonomyPickerWebPart.ts), pass the context to React component.
  1. export default class PnPTaxonomyPickerWebPart extends BaseClientSideWebPart<IPnPTaxonomyPickerWebPartProps> {  
  2.   
  3.   public render(): void {  
  4.     const element: React.ReactElement<IPnPTaxonomyPickerWebPartProps> = React.createElement(  
  5.       PnPTaxonomyPicker,  
  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

 
Open the React component file at “src\webparts\pnPTaxonomyPicker\components\PnPTaxonomyPicker.tsx”
 
Add the below imports.
  1. import { TaxonomyPicker, IPickerTerms } from "@pnp/spfx-controls-react/lib/TaxonomyPicker";  
Use the TaxonomyPicker control in the render method as follows.
  1. export default class PnPTaxonomyPicker extends React.Component<IPnPTaxonomyPickerProps, {}> {  
  2.   public render(): React.ReactElement<IPnPTaxonomyPickerProps> {  
  3.     return (  
  4.       <div className={ styles.pnPTaxonomyPicker }>  
  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.               <TaxonomyPicker allowMultipleSelections={true}  
  12.                 termsetNameOrID="Countries"  
  13.                 panelTitle="Select Term"  
  14.                 label="Taxonomy Picker"  
  15.                 context={this.props.context}  
  16.                 onChange={this.onTaxPickerChange}  
  17.                 isTermSetSelectable={false} />  
  18.             </div>  
  19.           </div>  
  20.         </div>  
  21.       </div>  
  22.     );  
  23.   }  
  24. }  
Specify the term set value for the termsetNameOrID property as the managed metadata selection.
 
Implement onChange property to get the selected terms from the TaxonomyPicker.
  1. private onTaxPickerChange(terms : IPickerTerms) {  
  2.   console.log("Terms", terms);  
  3. }  

Define the State

 
Let us define the state to store the selected terms of information.
 
Add file IPnPTaxonomyPickerState.ts under folder “\src\webparts\pnPTaxonomyPicker\components\”.
  1. import { IPickerTerms } from "@pnp/spfx-controls-react/lib/TaxonomyPicker";  
  2.   
  3. export interface IPnPTaxonomyPickerState {  
  4.     selectedTerms: IPickerTerms;  
  5. }  
Update the React component “\src\webparts\pnPTaxonomyPicker\components\PnPTaxonomyPicker.tsx” to use the state.
  1. import * as React from 'react';  
  2. import styles from './PnPTaxonomyPicker.module.scss';  
  3. import { IPnPTaxonomyPickerProps } from './IPnPTaxonomyPickerProps';  
  4. import { IPnPTaxonomyPickerState } from './IPnPTaxonomyPickerState';  
  5. import { escape } from '@microsoft/sp-lodash-subset';  
  6.   
  7. // @pnp/sp imports    
  8. import { sp, Web } from '@pnp/sp';  
  9. import { getGUID } from "@pnp/common";  
  10.   
  11. import { TaxonomyPicker, IPickerTerms } from "@pnp/spfx-controls-react/lib/TaxonomyPicker";  
  12.   
  13. export default class PnPTaxonomyPicker extends React.Component<IPnPTaxonomyPickerProps, IPnPTaxonomyPickerState> {  
  14.   
  15.   constructor(props: IPnPTaxonomyPickerProps, state: IPnPTaxonomyPickerState) {  
  16.     super(props);  
  17.   
  18.     this.state = {  
  19.       selectedTerms: []  
  20.     };  
  21.   }  
  22.    .  
  23.    .  
  24.    .  
  25. }  

Define the controls

 
Let us add a button control. On click of the button, we will add the selected terms from taxonomy picker to the SharePoint list.
 
Open React component PnPTaxonomyPicker.tsx at folder “src\webparts\pnPTaxonomyPicker\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="addSelectedTerms"    
  3.   title="Add Selected Terms"    
  4.   onClick={this.addSelectedTerms}>    
  5.   Add Selected Terms    
  6. </DefaultButton>   
Implement the supporting methods as below.
  1. @autobind   
  2. private onTaxPickerChange(terms : IPickerTerms) {  
  3.   console.log("Terms", terms);  
  4.   this.setState({ selectedTerms: terms });  
  5. }  

Add Selected Terms to SharePoint List

 
We are adding the selected terms to the React state using the onTaxPickerChange method of TaxonomyPicker PnP control. Now, we will implement a logic to add the selected terms from React state to actual SharePoint list. We will define 2 managed metadata columns (single selection and multi-selection).
 
Add 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="addSelectedTerms"    
  3.   title="Add Selected Terms"    
  4.   onClick={this.addSelectedTerms}>    
  5.   Add Selected Terms    
  6. </DefaultButton>    
Implement addSelectedTerms method. 
  1. @autobind   
  2. private addSelectedTerms(): void {   
  3.   // Update single value managed metadata field, with first selected term  
  4.   sp.web.lists.getByTitle("SPFx Users").items.add({  
  5.     Title: getGUID(),  
  6.     FirstTerm: {   
  7.       __metadata: { "type""SP.Taxonomy.TaxonomyFieldValue" },  
  8.       Label: this.state.selectedTerms[0].name,  
  9.       TermGuid: this.state.selectedTerms[0].key,  
  10.       WssId: -1  
  11.     }  
  12.   }).then(i => {  
  13.       console.log(i);  
  14.   });   
  15.   
  16.   // Update multi value managed metadata field  
  17.   const spfxList = sp.web.lists.getByTitle('SPFx Users');    
  18.   
  19.   // If the name of your taxonomy field is SomeMultiValueTaxonomyField, the name of your note field will be SomeMultiValueTaxonomyField_0  
  20.   const multiTermNoteFieldName = 'Terms_0';  
  21.   
  22.   let termsString: string = '';  
  23.   this.state.selectedTerms.forEach(term => {  
  24.     termsString += `-1;#${term.name}|${term.key};#`;  
  25.   });  
  26.   
  27.   spfxList.getListItemEntityTypeFullName()  
  28.     .then((entityTypeFullName) => {  
  29.       spfxList.fields.getByTitle(multiTermNoteFieldName).get()  
  30.         .then((taxNoteField) => {  
  31.           const multiTermNoteField = taxNoteField.InternalName;  
  32.           const updateObject = {  
  33.             Title: 'Item title',   
  34.           };  
  35.           updateObject[multiTermNoteField] = termsString;  
  36.   
  37.           spfxList.items.add(updateObject, entityTypeFullName)  
  38.             .then((updateResult) => {  
  39.                 console.dir(updateResult);  
  40.             })  
  41.             .catch((updateError) => {  
  42.                 console.dir(updateError);  
  43.             });  
  44.         });  
  45.     });  
  46. }  

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  
FirstTerm   Managed Metadata   Set “Allow multiple values” to No  
Terms   Managed Metadata   Set “Allow multiple values” to Yes  
 

Test the PnP Taxonomy 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 PnPTaxonomyPicker) to page.
  5. Select the terms using taxonomy picker.
  6. Click “Add Selected Terms”.

    PnP Taxonomy Picker Control For SPFx

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

Summary

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