DEV Community

Guido Zambarda
Guido Zambarda

Posted on • Originally published at iamguidozam.blog on

Use Microsoft Graph Toolkit v.4 in a SharePoint Framework React solution

Introduction

It’s been a while after my last article regarding how to use MGT and I thought that a revamped article with the newest approach about using MGT in a SPFx React solution would be a good idea, so here we are!

After my previous article the package @microsoft/mgt-spfx has been discontinued and in place of that, starting from the version 4 of the MGT packages, a new approach has been introduced: the disambiguation approach.

This new approach aims to enable the developer to use the latest MGT component version in a same page where there are also other web parts that use an older version of the MGT package.

I’ve created a sample solution to demonstrate how this works, if you’re interested you can find it here.

The sample simply shows various instances of the Person control, this is because I want to dive in the how to instead of showing you the result.

Install the packages

After you’ve created your SPFx solution the first thing to do in order to use the Microsoft Graph Toolkit is to install the required packages, using NPM you can execute the following:

npm install @microsoft/mgt-element @microsoft/mgt-components @microsoft/mgt-sharepoint-provider @microsoft/mgt-spfx-utils @microsoft/mgt-react
Enter fullscreen mode Exit fullscreen mode

The last package specified is required only if the solution will be using React.

Since the new packages utilize modern JavaScript you will have to configure Webpack to process it, I will cover later how to configure your gulpfile.js but for now install also the babel packages to handle that:

npm i --save-dev babel-loader@8.3.0 @babel/plugin-transform-optional-chaining @babel/plugin-transform-nullish-coalescing-operator @babel/plugin-transform-logical-assignment-operators
Enter fullscreen mode Exit fullscreen mode

Web part class

In the web part class that instantiate your custom component there are some changes that needs to be made in order to use version 4 of the MGT packages.

Imports

First of all you need to import some classes and methods and those are the following:

import { Providers, customElementHelper } from "@microsoft/mgt-element";
import { SharePointProvider } from "@microsoft/mgt-sharepoint-provider";
import { lazyLoadComponent } from "@microsoft/mgt-spfx-utils";
Enter fullscreen mode Exit fullscreen mode

Disambiguation

After the imports is time to define the disambiguation key, which is a string of your choice, and this is achieved using the customElementHelper object and specifying the disambiguation string that you want to use:

customElementHelper.withDisambiguation("updated-basic-mgt-sample");
Enter fullscreen mode Exit fullscreen mode

This code will be placed outside of the web part class.

Load the custom component

The next thing is to define the asynchronous import of the custom component, this can be defined outside of the web part class as following:

const CustomReactComponent = React.lazy(() =>
  import(
    /* webpackChunkName: 'mgt-react-component' */
    "./components/UpdatedBasicMgtSample"
));
Enter fullscreen mode Exit fullscreen mode

The string is the relative file path to the component control that you want to use inside of the web part class, in this case I’ve used ./components/UpdatedBasicMgtSample as the relative path to the component of my sample solution.

Keep in mind that the webpackChunkName comment should be specified, otherwise you would get a warning from Webpack while compiling the solution.

The render and onInit methods

Finally, inside the web part class, there are two methods that need to be implemented in a specific fashion and those are the render method and the onInit method.

render

The render method will load the previously imported custom component using the previously defined CustomReactComponent:

public render(): void {
  // Lazy load the component
  const element = lazyLoadComponent(CustomReactComponent, {
    description: strings.Description,
  });

  ReactDom.render(element, this.domElement);
}
Enter fullscreen mode Exit fullscreen mode

As you can see here we use the previously imported lazyLoadComponent method from the @microsoft/mgt-spfx-utils package to load the custom component and set the component properties.

onInit

Inside the onInit method we will simply, and as with the older version of the MGT packages, instantiate the SharePoint provider of MGT to be used inside of our web part. This can be achieved by setting the SharePointProvider as the MGT globalProvider:

protected async onInit(): Promise<void> {
  if (!Providers.globalProvider) {
    Providers.globalProvider = 
      new SharePointProvider(this.context);
  }
  return super.onInit();
}
Enter fullscreen mode Exit fullscreen mode

Custom component

The custom component is intended as the component that will be shown in the web part and that is, in this sample solution, the UpdatedBasicMgtSample component. The component simply uses the MGT Person control importing it with the code:

import { Person } from '@microsoft/mgt-react';
Enter fullscreen mode Exit fullscreen mode

And using it in the render method:

public render(): React.ReactElement<IUpdatedBasicMgtSampleProps> {
  // Use the Person MGT react control to display the current user
  return (
    <section className={styles.updatedBasicMgtSample}>
      <h2>{strings.Title}</h2>
      <div>
        <p>{this.props.description}</p>
      </div>
      <Person personQuery="me" />
      <Person personQuery="me" view={"oneline"} />
      <Person personQuery="me" view={"twolines"} />
      <Person personQuery="me" view={"threelines"} />
    </section>
  );
}
Enter fullscreen mode Exit fullscreen mode

I will not cover in detail this component since this is not the scope of the article but if you’re interested in knowing more check out the official documentation here.

Webpack configuration

As said before, there’s some Webpack configuration to be made in order to support modern JavaScript, it’s as easy as copy and paste in the end, but it’s a required step to support the latest technology. The changes to support modern JavaScript have to be made in the gulpfile.js file and you need to add the following code before initializing gulp:

const path = require("path");
const litFolders = [
  `node_modules${path.sep}lit${path.sep}`,
  `node_modules${path.sep}@lit${path.sep}`,
  `node_modules${path.sep}lit-html${path.sep}`
];
build.configureWebpack.mergeConfig({
  additionalConfiguration: generatedConfiguration => {
    generatedConfiguration.module.rules.push({
      test: /\.js$/,
      include: resourcePath => 
        litFolders.some(litFolder => resourcePath.includes(litFolder)),
      use: {
        loader: 'babel-loader',
        options: {
          plugins: [
            '@babel/plugin-transform-optional-chaining',
            '@babel/plugin-transform-nullish-coalescing-operator',
            '@babel/plugin-transform-logical-assignment-operators'
          ]
        }
      }
    });
    return generatedConfiguration;
  }
});
Enter fullscreen mode Exit fullscreen mode

Once this is done you can build and test your solution!

Conclusions

The new approach of the Microsoft Graph Toolkit introduced with version 4 is a little bit more complex than before but it surely is of help when you have multiple versions of MGT in your SharePoint’s web parts.

I took the idea of this article from the Microsoft official documentation that you can find here, in case you want to dive a little more about this new approach.

Hope this helps!

Top comments (0)