Display Group Members Using Graph API In SharePoint Framework

In this article, you will see how to display group members using Graph API in SharePoint Framework by performing the following tasks,
  • Prerequisites
  • Create SPFx solution
  • Implement SPFx solution
  • Deploy the solution
  • Approve Graph API Permissions
  • Test the webpart

Display Group members

 
Group members (current site group ID is considered) are displayed using Fluent UI Persona control.
 
Display Group Members Using Graph API In SharePoint Framework
 
Prerequisites

Create SPFx solution

 
Open Node.js command prompt.
 
Create a new folder.
 
>md spfx-fluentui-samples
 
Navigate to the folder.
 
>cd spfx-fluentui-samples
 
Execute the following command to create SPFx webpart.
 
>yo @microsoft/sharepoint
 
Enter all the required details to create a new solution as shown below.
 
Display Group Members Using Graph API In SharePoint Framework 
 
Yeoman generator will perform 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 SPFx solution

 
Execute the following command to install Microsoft Graph Typings.
 
> npm install @microsoft/microsoft-graph-types
 
Folder Structure
 
Display Group Members Using Graph API In SharePoint Framework 
 
Open package-solution.json “config\package-solution.json” file and update the code as shown below.
 
Note
Click here to view the permissions required to get group members.
  1. {  
  2.   "$schema""https://developer.microsoft.com/json-schemas/spfx-build/package-solution.schema.json",  
  3.   "solution": {  
  4.     "name""fluentui-persona-client-side-solution",  
  5.     "id""b04ff590-8d45-4578-9610-ba077ad203ec",  
  6.     "version""1.0.0.0",  
  7.     "includeClientSideAssets"true,  
  8.     "isDomainIsolated"false,  
  9.     "webApiPermissionRequests": [  
  10.       {  
  11.         "resource""Microsoft Graph",  
  12.         "scope""User.ReadBasic.All"  
  13.       },  
  14.       {  
  15.         "resource""Microsoft Graph",  
  16.         "scope""User.Read.All"  
  17.       },  
  18.       {  
  19.         "resource""Microsoft Graph",  
  20.         "scope""GroupMember.Read.All"  
  21.       },  
  22.       {  
  23.         "resource""Microsoft Graph",  
  24.         "scope""Group.Read.All"  
  25.       },  
  26.       {  
  27.         "resource""Microsoft Graph",  
  28.         "scope""Directory.Read.All"  
  29.       }  
  30.     ]  
  31.   },  
  32.   "paths": {  
  33.     "zippedPackage""solution/fluentui-persona.sppkg"  
  34.   }  
  35. }  
Create a new folder named as “models” inside src\webparts\personacontrol folder. Create a new file named as IPerson.ts. Open “src\webparts\personaControl\models\IPerson.ts” file and update the code as shown below.
  1. import { Guid } from "@microsoft/sp-core-library";  
  2.   
  3. export interface IPerson {  
  4.     id: Guid;  
  5.     displayName: string;  
  6.     department?: string;  
  7.     email?: string;  
  8. }  
Create a new file named as Dictionary.ts under models folder. Open “src\webparts\personaControl\models\Dictionary.ts” file and update the code as shown below.
  1. export interface Dictionary<T> {  
  2.     [key: string]: T | undefined;  
  3. }  
Create a new file named as IPersonaControlState.ts under components folder. Open “src\webparts\personaControl\components\IPersonaControlState.ts” file and update the code as shown below.
  1. import { IPerson } from "../models/IPerson";  
  2. import { Dictionary } from "../models/Dictionary";  
  3.   
  4. export interface IPersonaControlState {  
  5.   members: Dictionary<IPerson>;  
  6. }  
Open props file “src\webparts\personaControl\components\IPersonaControlProps.ts” file and update the code as shown below.
  1. import { MSGraphClient } from '@microsoft/sp-http';  
  2. import { Guid } from '@microsoft/sp-core-library';  
  3.   
  4. export interface IPersonaControlProps {  
  5.   graphHttpClient: MSGraphClient;  
  6.   groupId: Guid;  
  7. }  
Open “src\webparts\personaControl\PersonaControlWebPart.ts” file and update the following.
  • Import modules
  • Update the OnInit method
Import modules,
  1. import { MSGraphClient } from '@microsoft/sp-http';  
Update the OnInit method,
  1. private _graphHttpClient: MSGraphClient;  
  2.   
  3. protected onInit(): Promise<void> {  
  4.   return new Promise((resolve, reject) => {  
  5.     this.context.msGraphClientFactory.getClient().then(client => {  
  6.       this._graphHttpClient = client;  
  7.       resolve();  
  8.     }).catch(error => {  
  9.       console.log(error);  
  10.       reject(error);  
  11.     });  
  12.   });  
  13. }  
Update the Render method,
  1. public render(): void {  
  2. const element: React.ReactElement<IPersonaControlProps> = React.createElement(  
  3.   PersonaControl,  
  4.   {  
  5.     graphHttpClient: this._graphHttpClient,  
  6.     groupId: this.context.pageContext.site.group.id  
  7.   }  
  8. );  
  9.   
  10. ReactDom.render(element, this.domElement);  
Update the React component (src\webparts\personaControl\components\PersonaControl.tsx),
  1. import * as React from 'react';  
  2. import styles from './PersonaControl.module.scss';  
  3. import { IPersonaControlProps } from './IPersonaControlProps';  
  4. import { IPersonaControlState } from './IPersonaControlState';  
  5. import { escape } from '@microsoft/sp-lodash-subset';  
  6. import { IPerson } from "../models/IPerson";  
  7. import { Dictionary } from "../models/Dictionary";  
  8. import { Persona, PersonaSize, PersonaPresence } from 'office-ui-fabric-react/lib/Persona';  
  9. import { Stack, IStackStyles, IStackTokens } from 'office-ui-fabric-react/lib/Stack';  
  10. import { Link } from 'office-ui-fabric-react/lib/Link';  
  11. import { Icon } from 'office-ui-fabric-react/lib/Icon';  
  12. import { mergeStyles, DefaultPalette } from 'office-ui-fabric-react/lib/Styling';  
  13.   
  14. const iconClass = mergeStyles({  
  15.   fontSize: 25,  
  16.   height: 25,  
  17.   width: 25,  
  18.   margin: '0 25px',  
  19. });  
  20.   
  21. // Styles definition  
  22. const stackStyles: IStackStyles = {  
  23.   root: {  
  24.     width: 500,  
  25.   },  
  26. };  
  27.   
  28. export default class PersonaControl extends React.Component<IPersonaControlProps, IPersonaControlState> {  
  29.   constructor(props: IPersonaControlProps, state: IPersonaControlState) {  
  30.     super(props);  
  31.     this.state = {  
  32.       members: undefined  
  33.     };  
  34.   }  
  35.   
  36.   private async _getMembers(): Promise<Dictionary<IPerson>> {  
  37.     const endpoint: string = `/groups/${this.props.groupId}/members?$select=id,displayName,department,mail,photo`;  
  38.     const response: any = await this.props.graphHttpClient.api(endpoint).get();  
  39.     const graphResponse: any = response.value;  
  40.   
  41.     let peopleDictionary: Dictionary<IPerson> = {};  
  42.     graphResponse.map(user => {  
  43.       const person: IPerson = {  
  44.         id: user.id, displayName: user.displayName, department: user.department, email: user.mail  
  45.       };  
  46.       peopleDictionary[person.id.toString()] = person;  
  47.     });  
  48.   
  49.     return peopleDictionary;  
  50.   }  
  51.   
  52.   public async componentDidMount(): Promise<void> {  
  53.     const members: Dictionary<IPerson> = await this._getMembers();  
  54.     this.setState({  
  55.       members: members  
  56.     });  
  57.   }  
  58.   
  59.   public render(): React.ReactElement<IPersonaControlProps> {  
  60.     let members = [<div>Getting members...</div>];  
  61.   
  62.     if (this.state.members) {  
  63.       let membersArray: IPerson[] = [];  
  64.   
  65.       for (let key in this.state.members) {  
  66.         let value = this.state.members[key];  
  67.         membersArray.push(value);  
  68.       }  
  69.   
  70.       members = membersArray.map(member => {  
  71.         return (  
  72.           <Persona  
  73.             size={PersonaSize.size40}  
  74.             text={member.displayName}  
  75.             secondaryText={member.department}  
  76.           />  
  77.         );  
  78.       });  
  79.     }  
  80.   
  81.     return (  
  82.       <Stack>  
  83.         <span>Members</span>  
  84.         {members}  
  85.       </Stack>  
  86.     );  
  87.   }  
  88. }  

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
 
Upload the package file (sharepoint\solution\fluentui-persona.sppkg). Click Deploy.
 
Display Group Members Using Graph API In SharePoint Framework 
 

Approve Graph API permission

 
Navigate to SharePoint Admin center, click API access in the left navigation. Select the permission requested and click Approve.
 
Display Group Members Using Graph API In SharePoint Framework
 
Display Group Members Using Graph API In SharePoint Framework 
 

Test the webpart

 
Navigate to the SharePoint site and add the app.
 
Display Group Members Using Graph API In SharePoint Framework 
 
Navigate to the page and add the webpart.
 
Display Group Members Using Graph API In SharePoint Framework 
 

Summary

 
Thus, in this article, you saw how to display group members using Graph API in SharePoint Framework.