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
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.
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
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.
- {
- "$schema": "https://developer.microsoft.com/json-schemas/spfx-build/package-solution.schema.json",
- "solution": {
- "name": "fluentui-persona-client-side-solution",
- "id": "b04ff590-8d45-4578-9610-ba077ad203ec",
- "version": "1.0.0.0",
- "includeClientSideAssets": true,
- "isDomainIsolated": false,
- "webApiPermissionRequests": [
- {
- "resource": "Microsoft Graph",
- "scope": "User.ReadBasic.All"
- },
- {
- "resource": "Microsoft Graph",
- "scope": "User.Read.All"
- },
- {
- "resource": "Microsoft Graph",
- "scope": "GroupMember.Read.All"
- },
- {
- "resource": "Microsoft Graph",
- "scope": "Group.Read.All"
- },
- {
- "resource": "Microsoft Graph",
- "scope": "Directory.Read.All"
- }
- ]
- },
- "paths": {
- "zippedPackage": "solution/fluentui-persona.sppkg"
- }
- }
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.
- import { Guid } from "@microsoft/sp-core-library";
-
- export interface IPerson {
- id: Guid;
- displayName: string;
- department?: string;
- email?: string;
- }
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.
- export interface Dictionary<T> {
- [key: string]: T | undefined;
- }
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.
- import { IPerson } from "../models/IPerson";
- import { Dictionary } from "../models/Dictionary";
-
- export interface IPersonaControlState {
- members: Dictionary<IPerson>;
- }
Open props file “src\webparts\personaControl\components\IPersonaControlProps.ts” file and update the code as shown below.
- import { MSGraphClient } from '@microsoft/sp-http';
- import { Guid } from '@microsoft/sp-core-library';
-
- export interface IPersonaControlProps {
- graphHttpClient: MSGraphClient;
- groupId: Guid;
- }
Open “src\webparts\personaControl\PersonaControlWebPart.ts” file and update the following.
- Import modules
- Update the OnInit method
Import modules,
- import { MSGraphClient } from '@microsoft/sp-http';
Update the OnInit method,
- private _graphHttpClient: MSGraphClient;
-
- protected onInit(): Promise<void> {
- return new Promise((resolve, reject) => {
- this.context.msGraphClientFactory.getClient().then(client => {
- this._graphHttpClient = client;
- resolve();
- }).catch(error => {
- console.log(error);
- reject(error);
- });
- });
- }
Update the Render method,
- public render(): void {
- const element: React.ReactElement<IPersonaControlProps> = React.createElement(
- PersonaControl,
- {
- graphHttpClient: this._graphHttpClient,
- groupId: this.context.pageContext.site.group.id
- }
- );
-
- ReactDom.render(element, this.domElement);
Update the React component (src\webparts\personaControl\components\PersonaControl.tsx),
- import * as React from 'react';
- import styles from './PersonaControl.module.scss';
- import { IPersonaControlProps } from './IPersonaControlProps';
- import { IPersonaControlState } from './IPersonaControlState';
- import { escape } from '@microsoft/sp-lodash-subset';
- import { IPerson } from "../models/IPerson";
- import { Dictionary } from "../models/Dictionary";
- import { Persona, PersonaSize, PersonaPresence } from 'office-ui-fabric-react/lib/Persona';
- import { Stack, IStackStyles, IStackTokens } from 'office-ui-fabric-react/lib/Stack';
- import { Link } from 'office-ui-fabric-react/lib/Link';
- import { Icon } from 'office-ui-fabric-react/lib/Icon';
- import { mergeStyles, DefaultPalette } from 'office-ui-fabric-react/lib/Styling';
-
- const iconClass = mergeStyles({
- fontSize: 25,
- height: 25,
- width: 25,
- margin: '0 25px',
- });
-
-
- const stackStyles: IStackStyles = {
- root: {
- width: 500,
- },
- };
-
- export default class PersonaControl extends React.Component<IPersonaControlProps, IPersonaControlState> {
- constructor(props: IPersonaControlProps, state: IPersonaControlState) {
- super(props);
- this.state = {
- members: undefined
- };
- }
-
- private async _getMembers(): Promise<Dictionary<IPerson>> {
- const endpoint: string = `/groups/${this.props.groupId}/members?$select=id,displayName,department,mail,photo`;
- const response: any = await this.props.graphHttpClient.api(endpoint).get();
- const graphResponse: any = response.value;
-
- let peopleDictionary: Dictionary<IPerson> = {};
- graphResponse.map(user => {
- const person: IPerson = {
- id: user.id, displayName: user.displayName, department: user.department, email: user.mail
- };
- peopleDictionary[person.id.toString()] = person;
- });
-
- return peopleDictionary;
- }
-
- public async componentDidMount(): Promise<void> {
- const members: Dictionary<IPerson> = await this._getMembers();
- this.setState({
- members: members
- });
- }
-
- public render(): React.ReactElement<IPersonaControlProps> {
- let members = [<div>Getting members...</div>];
-
- if (this.state.members) {
- let membersArray: IPerson[] = [];
-
- for (let key in this.state.members) {
- let value = this.state.members[key];
- membersArray.push(value);
- }
-
- members = membersArray.map(member => {
- return (
- <Persona
- size={PersonaSize.size40}
- text={member.displayName}
- secondaryText={member.department}
- />
- );
- });
- }
-
- return (
- <Stack>
- <span>Members</span>
- {members}
- </Stack>
- );
- }
- }
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.
Approve Graph API permission
Navigate to SharePoint Admin center, click API access in the left navigation. Select the permission requested and click Approve.
Test the webpart
Navigate to the SharePoint site and add the app.
Navigate to the page and add the webpart.
Summary
Thus, in this article, you saw how to display group members using Graph API in SharePoint Framework.