Retrieve User Profile Properties Using SPFx And PnP JS In SharePoint Online

SharePoint Framework is the new development model in which a lot of work has been going on since it went for General Availability on Feb 23, 2017. It is a page and web part model that provides full support for client-side SharePoint development, easy integration with SharePoint data, and support for open source tooling. With the SharePoint Framework, you can use modern web technologies and tools in your preferred development environment to build productive experiences and apps in SharePoint.

In a previous article, we saw how to set up the development environment for SharePoint Framework. We also saw the basic Hello World web part creation and how to retrieve and display list items using SharePoint Framework. 

In this section, we will see another example of SPFx and PnP in action, here we will be using this combo to retrieve the user profile properties and display them in the web part. The major project files used in this solution have been zipped and uploaded along with this article. Feel free to download it. 

Create the Web Part Project

Spin up Node.js command prompt, using which we will be creating the Web part project structure. We can create the directory where we will be adding the solution, using the command given below.

md GetUserProfileProperties

Let’s move to the newly created working directory, using the command.

cd GetUserProfileProperties

SharePoint

We will then create the client Web part by running the Yeoman SharePoint Generator.

yo @microsoft/sharepoint

SharePoint

This will display the prompt which we will have to fill up so as to proceed with the project creation.

  • What is your solution name? : Set it to ‘GetUserProfileProperties’.

On pressing enter, we will be asked to chose the working folder for the project.

  • Where do you want to place your files? - Use current folder.
  • What framework would you like to start with? - Select “No javaScript web framework” for the time being, as this is a sample Web part.
  • What is your Webpart name? - We will specify it as ‘GetUserProfileProperties’ and press Enter.
  • What is your Webpart description? - We will specify it as ‘Retrieve User Properties using SharePoint Framework’.

    SharePoint
Edit the web part

Run code to open the project in Visual Studio Code.

SharePoint

Now, we have to load PnP JS file which we will use within the project to create a list. We will be using npm to add the PnP JS file as shown below.

npm install sp-pnp-js --save

SharePoint

Retrieve User Profile data

In order to use PnP methods, we can refer the PnP file in the project as below.

import * as pnp from 'sp-pnp-js';

We will then make use of the below function to fetch the user profile properties of the user and display it within the web part. Th pnp.sp.profiles.myProperties.get() will return the current user’s profile properties which can be iterated to return the required information. 

  1. private GetUserProperties(): void {  
  2.     sp.profiles.myProperties.get().then(function(result) {  
  3.         var userProperties = result.UserProfileProperties;  
  4.         var userPropertyValues = "";  
  5.         userProperties.forEach(function(property) {  
  6.             userPropertyValues += property.Key + " - " + property.Value + "<br/>";  
  7.         });  
  8.         document.getElementById("spUserProfileProperties").innerHTML = userPropertyValues;  
  9.     }).catch(function(error) {  
  10.         console.log("Error: " + error);  
  11.     });  
  12. }  
TS File content to retrieve User Profile Data

The entire TS file content is shown below. The this.GetUserProperties() in the render method will call the function that gets the User Profile properties of the user. It will be then displayed within the div element declared in the render method.

  1. import * as pnp from 'sp-pnp-js';  
  2. import {  
  3.     Version  
  4. } from '@microsoft/sp-core-library';  
  5. import {  
  6.     BaseClientSideWebPart,  
  7.     IPropertyPaneConfiguration,  
  8.     PropertyPaneTextField  
  9. } from '@microsoft/sp-webpart-base';  
  10. import {  
  11.     escape  
  12. } from '@microsoft/sp-lodash-subset';  
  13. import styles from './GetUserProfileProperties.module.scss';  
  14. import * as strings from 'getUserProfilePropertiesStrings';  
  15. import {  
  16.     IGetUserProfilePropertiesWebPartProps  
  17. } from './IGetUserProfilePropertiesWebPartProps';  
  18. export default class GetUserProfilePropertiesWebPart extends BaseClientSideWebPart < IGetUserProfilePropertiesWebPartProps > {  
  19.     private GetUserProperties(): void {  
  20.         sp.profiles.myProperties.get().then(function(result) {  
  21.             var userProperties = result.UserProfileProperties;  
  22.             var userPropertyValues = "";  
  23.             forEach(function(property) {  
  24.                 userPropertyValues += property.Key + " - " + property.Value + "<br/>";  
  25.             });  
  26.             getElementById("spUserProfileProperties").innerHTML = userPropertyValues;  
  27.         }).catch(function(error) {  
  28.             log("Error: " + error);  
  29.         });  
  30.     }  
  31.     public render(): void {  
  32.         domElement.innerHTML = `  
  33. <div class="${styles.helloWorld}">  
  34. <div class="${styles.container}">  
  35. <div class="ms-Grid-row ms-bgColor-themeDark ms-fontColor-white ${styles.row}">  
  36. <div class="ms-Grid-col ms-u-lg10 ms-u-xl8 ms-u-xlPusstrong ms-u-lgPusstrong">  
  37. <span class="ms-font-xl ms-fontColor-white" style="font-size:28px">Welcome to SharePoint Framework Development using PnP JS Library</span>  
  38. <p class="ms-font-l ms-fontColor-white" style="text-align: left">Demo : Retrieve User Profile Properties</p>  
  39. </div>  
  40. </div>  
  41. <div class="ms-Grid-row ms-bgColor-themeDark ms-fontColor-white ${styles.row}">  
  42. <div style="background-color:Black;color:white;text-align: center;font-weight: bold;font-size:18px;">User Profile Details</div>  
  43. <br>  
  44. <div id="spUserProfileProperties" />  
  45. </div>  
  46. </div>  
  47. </div>`;  
  48.         GetUserProperties();  
  49.     }  
  50.     protected get dataVersion(): Version {  
  51.         return Version.parse('1.0');  
  52.     }  
  53.     protected getPropertyPaneConfiguration(): IPropertyPaneConfiguration {  
  54.         return {  
  55.             pages: [{  
  56.                 header: {  
  57.                     description: strings.PropertyPaneDescription  
  58.                 },  
  59.                 groups: [{  
  60.                     groupName: strings.BasicGroupName,  
  61.                     groupFields: [  
  62.                         PropertyPaneTextField('description', {  
  63.                             label: strings.DescriptionFieldLabel  
  64.                         })  
  65.                     ]  
  66.                 }]  
  67.             }]  
  68.         };  
  69.     }  
  70. }  
Test the Web part in SharePoint Online

Now, let’s test the Web part in SharePoint Workbench available in SharePoint Online. Once we have logged into SharePoint Online, we can invoke the workbench by appending the text ‘_layouts/15/workbench.aspx’ to SharePoint Online URL. Add the web part to the page by selecting GetUserProfile icon.

SharePoint

This will add the web part to the page and it will fetch the user profile details of the user and display it.

SharePoint

The major project files used in this solution have been zipped and uploaded along with this article.

Summary

Thus, we saw how to retrieve user profile properties from SharePoint Online using SharePoint Framework and PnP JS. We will see more of SPFx in action in the upcoming articles.