How to use MS Graph Toolkit Get component in SharePoint Framework

Learn how to use Microsoft Graph Toolkit Get's component in a SharePoint Framework web par. And also learn how to declare the template for the Get component.

Recently I just prepared a prototype to show all AAD users in a SharePoint Framework Web part. Immediately I got an idea to use Microsoft graph Toolkit to display the users, without much effort.

So, I used the yeoman generator command yo @microsoft/SharePoint to generate the SharePoint Web part with React support.

Then install the below packages to use Microsoft Graph Toolkit in a web part

npm i @microsoft/mgt-spfx
npm i @microsoft/mgt-react

After installing the packages, open the *WebPart.ts file and declare the provider to use the Microsoft Graph API,

[code lang=”js”]
import { Providers, SharePointProvider } from ‘@microsoft/mgt-spfx’;

protected async onInit(): Promise<void> {
if (!Providers.globalProvider) {
Providers.globalProvider = new SharePointProvider(this.context);

Then, open the component file *.tsx file and import the Toolkit web components in the file

[code lang=”js”]
import { Person, Get } from ‘@microsoft/mgt-react/dist/es6/spfx’;
import { MgtTemplateProps } from ‘@microsoft/mgt-react’;
import { ViewType } from ‘@microsoft/mgt-spfx’

Now, we have imported Get Component to send the get request to Graph API and the Person component is used to

  • display the Person card based on the output.
  • To render the output from Get, we must specify the template MgtTemplateProps component
  • ViewType is an attribute used in the Person component.

Then add the Get component to the Component file,

[code lang=”html”]
<Get resource="/users" version="v1.0" scopes={getscopes}>
<TemplatePerson template="value"/>

  • getscopes is an array variable to specify the consent required for running the get request.

Before the class in web part, specify the Template component like below

[code lang=”js”]
// Used to set scope for the Get element
let getscopes = ["User.Read.All"];

//Template declaration for Get element
const TemplatePerson = (props: MgtTemplateProps) =&gt; {
const person = props.dataContext;
return <div>
<Person userId={person.userPrincipalName} view={ViewType.twolines}></Person>

After completing the code, save and run the web part by using gulp serve. Then open the Workbench in a SharePoint site and test the web part.

Now, the web part looks like below, without spending too much time and also with less number of code,Get Component output in SPFX

Here is the full Web Part component code below,

MSGraph Get Component in SPFX

Hope you enjoyed this post. Happy coding :)

Shantha Kumar
Shantha Kumar
Articles: 280