SPFx – Using MSGraph Toolkit


Hi Friends, let us see how we can use MSGraph Toolkit (MGT) in SharePoint Framework. This will give you a starting point to use the MGT with some configuration change and as a add-on will also focus on using Theme to style to the MGT component.

What is MGT?

It is a collection of reusable, framework-agnostic web components and helpers for accessing and working with Microsoft Graph. With the use of these components, the developers can use it without writing any boiler plate code for authentication and authorization and in SPFx its very easy compared to the usage in normal nodejs application or in other applications. There are few components in MGT and further more to come. Please see the reference links section to view the documentation.

Focus on the Code

Let us start by creating a new web part project using yeoman SharePoint generator, before that create a folder where you want to create the web part. Navigate to that folder and run the below command.

yo @microsoft/sharepoint

The generator will asks you couple of questions,

  • Enter the webpart name as your solution name, and then select Enter.
  • Select Create a subfolder with solution name for where to place the files.
  • Select N to allow the solution to be deployed to all sites immediately.
  • Select Y on the question if solution contains unique permissions.
  • Enter the webpart name
  • Enter the webpart description
  • Choose the framework as ‘React

Once the project is created, we have to do some minor changes to the existing configuration and had to install some dependent libraries. Copy-paste the below command to install the latest compiler

npm install @microsoft/rush-stack-compiler-3.7 --save-dev

Do the below change in the tsconfig.json file. Make sure your reference is from the latest compiler module.

"extends": "./node_modules/@microsoft/rush-stack-compiler-3.7/includes/tsconfig-web.json"

You may get some error on the tslint configuration because of the latest compiler, if you get any issue like the below

Error - [tslint] no-use-before-declare is deprecated.

Open the tslint.json file and remove the property no-use-before-declare

Copy-paste the below code to install the MGT module to use in our web part.

npm install @microsoft/mgt --save

Make sure the package-solution.json file looks like the below except the default id, version properties.

    "$schema": "https://developer.microsoft.com/json-schemas/spfx-build/package-solution.schema.json",
    "solution": {
        "name": "spfx-demos-client-side-solution",
        "id": "429c0295-f304-42fc-bdb0-7abdd5bce7c4",
        "version": "",
        "includeClientSideAssets": true,
        "isDomainIsolated": false,
        "webApiPermissionRequests": [
                "resource": "Microsoft Graph",
                "scope": "User.Read.All"
                "resource": "Microsoft Graph",
                "scope": "User.ReadBasic.All"
                "resource": "Microsoft Graph",
                "scope": "Presence.Read"
                "resource": "Microsoft Graph",
                "scope": "Presence.Read.All"
    "paths": {
        "zippedPackage": "solution/spfx-demos.sppkg"

We have requested for some of the permissions from MSGraph to display the user information, these permissions has to be approved at the time of the app deployment. Since we are just displaying the user info, we had requested only for the read permission of the user. Different component would require different permissions. Make sure to grant these permissions when you are trying out the code with different components.

Add the following imports to the webpart.ts file. This imports the Theme related properties and MGT Providers for SharePoint.

import { ThemeProvider, IReadonlyTheme, ThemeChangedEventArgs } from '@microsoft/sp-component-base';
import { Providers, SharePointProvider } from '@microsoft/mgt';

Copy-paste the below code just above the render method in the webpart.ts file.

private themeProvider: ThemeProvider;
    private theme: IReadonlyTheme;

    protected onInit(): Promise<void> {
        this.themeProvider = this.context.serviceScope.consume(ThemeProvider.serviceKey);
        this.theme = this.themeProvider.tryGetTheme();
        this.themeProvider.themeChangedEvent.add(this, this.onThemeChanged);
        Providers.globalProvider = new SharePointProvider(this.context);
        return super.onInit();

    private onThemeChanged(args: ThemeChangedEventArgs) {
        this.theme = args.theme;
  • Declared the variables for the theme properties.
  • In OnInit method, assigned the theme properties to the variable, declared the themeChangedEvent to modify the design of the component whenever a theme is changed, and set the provider to SharePoint Provider with the current context to use the MGT components
  • On the themeChanged event, assign the theme and render the component again.

Declare a theme property to be passed to the parent component from the webpart.ts file.

import { IReadonlyTheme } from '@microsoft/sp-component-base';
export interface IHelloMgtProps {
    description: string;
    themeVariant: IReadonlyTheme | undefined;

Let us do some changes on the webpart.tsx file

Add the following imports to use the theme styles inside the tsx file instead of using the scss file. You may also use the scss file to customize the component which is also covered in this post.

import { mergeStyleSets } from 'office-ui-fabric-react/lib/Styling';

Copy-paste the below code to use the MGT component, since it is web-component we have to define the component globally to use it in the SharePoint Framework.

declare global {
    namespace JSX {
        interface IntrinsicElements {
            'mgt-person': any;

Replace the render method with the below code.

return (
            <div className={styles.helloMgt}>
                <div className={styles.container}>
                    <div className={styles.row}>
                        <div className={styles.column}>
                            <div className={styles.divRow}>
                                <mgt-person class={styles.personStyle} person-query="me"
                                    show-name show-email></mgt-person>
                            <div className={styles.divRow}>
                                <mgt-person class={this.personStyle.themeStyle} person-details={JSON.stringify(this.personDetail)} view="twolines"></mgt-person>

Copy-paste the below code before the render method.

private personDetail: any = {
        displayName: 'Pradeep Gupta',
        mail: 'This is a random text'
    private personStyle = mergeStyleSets({
        themeStyle: {
            backgroundColor: this.props.themeVariant.palette.themePrimary

Let us see what we had done in the webpart.tsx file. We have used the component named mgt-person to display the person detail. We have used 2 component, the first is using the graph query to display the current user with custom style and the second is using the hard-coded variable to render the person component using current theme colors.

Add the below code in the webpart.module.scss file

.divRow {
      padding: 10px;
  .personStyle {
    --font-family: 'Comic Sans MS', cursive, sans-serif;
    --color: white;
    --avatar-size: 60px;
    --font-size: 20px;
    --line2-color: white;
    --avatar-border-radius: 10% 35%;
    --line2-text-transform: uppercase;

The components are more powerful and the graph team had covered a lot of boiler plate code and made it easy for the developers to use the component with less configuration and properties and with minimal lines of code which would save a lot of time. Please don’t forget to check the reference links


Reference Links

Source Code

The source code along with other samples can be found in the below github link.


Happy Coding…


2 thoughts on “SPFx – Using MSGraph Toolkit

  1. Pingback: SPFx – MGT Person component | Knowledge Share

  2. Pingback: SPFx-MSGraph Toolkit using @microsoft/mgt-spfx & @microsoft/mgt-react | Knowledge Share

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s