Use Microsoft Graph Toolkit with SPFx and React

Published by

on

Microsoft Graph Toolkit aka MGT can be used inside an SPFx solution in a quick and easy way and I’m here to show you how.

This sample shows how to use the Person MGT control inside a React SPFx web part, the result will be the following:

Where we simply show the current user in different possible fashions.

How to achieve the result

After creating an SPFx solution with a web part you can import the required packages:

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

Once the packages are added you need to specify the provider in the web part class element, to use it you have to import the SharePointProvider:

import { Providers, SharePointProvider } from '@microsoft/mgt-spfx';

After that you have to initialize the provider if not already instantiated:

protected async onInit(): Promise<void> {
// Initialize the MGT Provider
if (!Providers.globalProvider) {
Providers.globalProvider = new SharePointProvider(this.context as any);
}
}

In the web part component import the controls you want to use, in this sample we import the Person control and the ViewType:

import { Person } from '@microsoft/mgt-react/dist/es6/spfx';

import { ViewType } from '@microsoft/mgt-spfx';

In the render method you can then use the control:

<section className={styles.basicMgtSample}>
<h2>Basic MGT Sample</h2>
<Person personQuery="me" view={ViewType.image} />
<Person personQuery="me" view={ViewType.oneline} />
<Person personQuery="me" view={ViewType.twolines} />
<Person personQuery="me" view={ViewType.threelines} />
</section>

Noteworthy

Noteworthy

All the MGT controls relies on the permissions given to the Entra ID application “SharePoint Online Client Extensibility Web Application Principal”, to check which permissions you need keep in mind to check the official documentation of the control you’re using.

Conclusions

If you want to discover more you can check the official article here.

NB: to use the MGT SharePoint package with your solution you need to deploy it in the App Catalog of your target tenant and pay attention that you can have only one version of the @microsoft/mgt-spfx package installed. You can download the package to install it in the App Catalog from the official repository here and remember to deploy it for all sites.

If you want to check the sample code of this post you can find it here.

Hope this helps!