DEV Community

Guido Zambarda
Guido Zambarda

Posted on • Originally published at iamguidozam.blog on

Use Microsoft Graph Toolkit with SPFx and React

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-spfxnpm install @microsoft/mgt-react
Enter fullscreen mode Exit fullscreen mode

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';
Enter fullscreen mode Exit fullscreen mode

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);
    }
  }
Enter fullscreen mode Exit fullscreen mode

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';
Enter fullscreen mode Exit fullscreen mode

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>
Enter fullscreen mode Exit fullscreen mode

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 that helps!

Top comments (0)