SPFx-MSGraph Toolkit PeoplePicker Control

Introduction

Hi friends, in my previous post I walk you through the steps on how you can leverage MSGraph Toolkit components in SharePoint Framework project with minimal configuration. Now let us see how we can use the PeoplePicker control from MSGraph Toolkit in action, its properties and how we can customize the control.

Focus on the Code

Let us start by creating a new web part project using yeoman SharePoint generator, before that create a folder where you want to create the web part. Navigate to that folder and run the below command.

yo @microsoft/sharepoint

The generator will asks you couple of questions,

  • Enter the webpart name as your solution name, and then select Enter.
  • Select Create a subfolder with solution name for where to place the files.
  • Select N to allow the solution to be deployed to all sites immediately.
  • Select N on the question if solution contains unique permissions.
  • Enter the webpart name
  • Enter the webpart description
  • Choose the framework as ‘React

NoteI have used @microsoft/generator-sharepoint version 1.12.1

Once the project is created, make sure the web part is running without any issue. Its better to actually run the vanilla web part once it is created. Once the verification is done, install the below packages

Once the above packages are installed, you should have the package.json file like the below

{
    "name": "graph-toolkit-demo",
    "version": "0.0.1",
    "private": true,
    "main": "lib/index.js",
    "scripts": {
        "build": "gulp bundle",
        "clean": "gulp clean",
        "test": "gulp test"
    },
    "dependencies": {
        "@microsoft/mgt-react": "^2.3.0",
        "@microsoft/mgt-spfx": "^2.3.0",
        "@microsoft/sp-core-library": "1.12.1",
        "@microsoft/sp-lodash-subset": "1.12.1",
        "@microsoft/sp-office-ui-fabric-core": "1.12.1",
        "@microsoft/sp-property-pane": "1.12.1",
        "@microsoft/sp-webpart-base": "1.12.1",
        "office-ui-fabric-react": "7.156.0",
        "react": "16.9.0",
        "react-dom": "16.9.0"
    },
    "devDependencies": {
        "@types/react": "16.9.36",
        "@types/react-dom": "16.9.8",
        "@microsoft/sp-build-web": "1.12.1",
        "@microsoft/sp-tslint-rules": "1.12.1",
        "@microsoft/sp-module-interfaces": "1.12.1",
        "@microsoft/sp-webpart-workbench": "1.12.1",
        "@microsoft/rush-stack-compiler-3.7": "0.2.3",
        "gulp": "~4.0.2",
        "ajv": "~5.2.2",
        "@types/webpack-env": "1.13.1"
    }
}

Here I have named my web part as graph-toolkit-demo.

Now we have to update our code to authenticate to Microsoft Identity to access the Microsoft Graph API. There is no complication and nothing to worry on the authentication or setup, all are taken care by the providers which comes with the package that we installed above. We just need to use the right providers. Since we are using SPFx, we need to use the SharePoint Provider. This can be achieved with just a single line of code which is shown below. Update your <webpart>.ts file with the below code.

import { Providers, SharePointProvider } from '@microsoft/mgt-spfx';
protected async onInit() {
    if (!Providers.globalProvider) {
        Providers.globalProvider = new SharePointProvider(this.context);
    }
}

So with the above code, the authentication is set. Now we can see how we can use the components in our <webpart>.tsx file. Before modifying the web part file, we need to create some folders and files which makes it easy for maintaining the controls and for re-usability.

Create a folder named ToolkitControl in the src folder. Add the following files

  • Graph.PeoplePicker.tsx
  • controlStyles.module.scss

The style class is common for all the controls and for each control you can create a separate tsx file and implement the business logic.

Update Graph.PeoplePicker.tsx with the below code

import * as React from 'react';
import { useState, useEffect } from 'react';
import styles from './controlStyles.module.scss';
import { PeoplePicker } from '@microsoft/mgt-react/dist/es6/spfx';
import { PersonType } from '@microsoft/mgt-spfx';

export const GraphPeoplePicker: React.FC<{}> = (props) => {
    const [selPeople, setSelPeople] = useState<string[]>([]);

    const _onSelectionChanged = (e: any) => {
        let selusers: string[] = [];
        if (e.detail && e.detail.length > 0) {
            e.detail.map(user => {
                selusers.push(user.userPrincipalName);
            });
        }
        console.log(selusers);
        setSelPeople(selusers);
    };

    useEffect(() => {

    }, [selPeople]);

    return (
        <div className={styles.peoplePickerContainer}>
            <p>All Users and Groups</p>
            <PeoplePicker type={PersonType.any} placeholder="Select users or groups!"
                selectionChanged={_onSelectionChanged} />
            <div className={styles.selUsers}><b>Selected Users</b>: {selPeople.length > 0 ? selPeople.join(', ') : 'No users selected!'}</div>
            <p>Group Users</p>
            <PeoplePicker type={PersonType.person} placeholder="Select users from group!" groupId={'a5bf1924-0121-449c-8a94-515025544596'} />
            <div className={styles.customStyledPicker}>
                <p>Custom Style applied</p>
                <PeoplePicker />
            </div>
        </div>
    );
};

Below are done in the above code

  • We have imported the correct reference to the PeoplePicker component from ‘@microsoft/mgt-react/dist/es6/spfx
  • Declared a state variable to store the selected people email address. You can change it to store few properties.
  • Declared a method _onSelectionChanged which will be invoked each time there is a change in the selection to the control. If the users are selected then the properties are added to the state variable.
  • Render the PeoplePicker control with different properties. I have used thrice to show you how you can use the control properties and custom styles.

Note: The links to the documentation is mentioned in the reference section below.

Update controlStyles.module.scss file

@import '~office-ui-fabric-react/dist/sass/References.scss';

.peoplePickerContainer {
    p {
        color: black;
        font-size: 15px;
        font-weight: bold;
    }
    .selUsers {
        color: black;
    }
    .customStyledPicker {
        mgt-people-picker {
            --input-border: 2px rgba(255, 255, 255, 0.5) solid; /* sets all input area border */
        
              /* OR individual input border sides */
            --input-border-bottom: 2px rgba(255, 255, 255, 0.5) solid;
            --input-border-right: 2px rgba(255, 255, 255, 0.5) solid;
            --input-border-left: 2px rgba(255, 255, 255, 0.5) solid;
            --input-border-top: 2px rgba(255, 255, 255, 0.5) solid;
        
            --input-background-color: #1f1f1f; /* input area background color */
            --input-border-color--hover: #008394; /* input area border hover color */
            --input-border-color--focus: #0f78d4; /* input area border focus color */
        
            --dropdown-background-color: white; /* selection area background color */
            --dropdown-item-hover-background: #85abd1; /* person background color on hover */
            
            --selected-person-background-color: #f1f1f1; /* person item background color */
            
            --color: white; /* input area border focus color */
            --placeholder-color: #f1f1f1; /* placeholder text color */
            --placeholder-color--focus: rgba(255, 255, 255, 0.8); /* placeholder text focus color */
        }
    }
}

The control is ready and now we can render the control in the actual webpart.tsx file. Update the file with the required import and the control inside the render method.

import { GraphPeoplePicker } from '../../../ToolkitControls/Graph.PeoplePicker';
public render(): React.ReactElement<IGraphToolkitDemoProps> {
    return (
        <div className={styles.graphToolkitDemo}>
            <div className={styles.container}>
                <div className={styles.row}>
                    <div className={styles.column}>
                        <GraphPeoplePicker />
                    </div>
                </div>
            </div>
        </div>
    );
}

Now the last and the most important for the Graph API to access the data. I think you figured it out, its the scopes. We have to define the scopes that are used by the control in the package-solution.json file.

"webApiPermissionRequests": [
            {
                "resource": "Microsoft Graph",
                "scope": "User.Read.All"
            },
            {
                "resource": "Microsoft Graph",
                "scope": "Group.Read.All"
            },
            {
                "resource": "Microsoft Graph",
                "scope": "User.ReadBasic.All"
            },
            {
                "resource": "Microsoft Graph",
                "scope": "People.Read"
            }
        ]

Thats it. You are done with the coding part and now comes the fun part. Execute the code and see how it renders. Make sure you approve the API requests in the SharePoint Admin Center.

Reference Links

Happy Coding…

Advertisement

2 thoughts on “SPFx-MSGraph Toolkit PeoplePicker Control

    • Hi, If you want to show the org chart once the user is selected, then you have to customize the template or add a new control below the people picker to show the org chart. I think once the user is selected in the people picker you can show the detailed popover where it shows all the information about the selected user, org chart and few other information too.

      Like

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s