SPFx-MSGraph Toolkit Get Control

Introduction

Hi friends, in one of my previous post I walk you through the steps on how you can leverage MSGraph Toolkit components in SharePoint Framework project with minimal configuration. Now let us see how we can use the Get control from MSGraph Toolkit in action, its properties and how we can customize the control.

This component is different from the other components. Other components will have some common endpoints to call with select or filter query and there are some default styles associated with the component and we can even customize it. Get component doesn’t have any common endpoint, you can can any api endpoint as long as the permissions are correctly configured and also, the component doesn’t have any default UI. The entire UI based on the response has to be designed by us which gives us more control compared to the rest of the toolkit components.

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 N on the question if solution contains unique permissions.
  • Enter the webpart name
  • Enter the webpart description
  • Choose the framework as ‘React

NoteI have used @microsoft/generator-sharepoint version 1.12.1

Once the project is created, make sure the web part is running without any issue. Its better to actually run the vanilla web part once it is created. Once the verification is done, install the below packages

Once the above packages are installed, you should have the package.json file like the below

{
    "name": "graph-toolkit-demo",
    "version": "0.0.1",
    "private": true,
    "main": "lib/index.js",
    "scripts": {
        "build": "gulp bundle",
        "clean": "gulp clean",
        "test": "gulp test"
    },
    "dependencies": {
        "@microsoft/mgt-react": "^2.3.0",
        "@microsoft/mgt-spfx": "^2.3.0",
        "@microsoft/sp-core-library": "1.12.1",
        "@microsoft/sp-lodash-subset": "1.12.1",
        "@microsoft/sp-office-ui-fabric-core": "1.12.1",
        "@microsoft/sp-property-pane": "1.12.1",
        "@microsoft/sp-webpart-base": "1.12.1",
        "office-ui-fabric-react": "7.156.0",
        "react": "16.9.0",
        "react-dom": "16.9.0"
    },
    "devDependencies": {
        "@types/react": "16.9.36",
        "@types/react-dom": "16.9.8",
        "@microsoft/sp-build-web": "1.12.1",
        "@microsoft/sp-tslint-rules": "1.12.1",
        "@microsoft/sp-module-interfaces": "1.12.1",
        "@microsoft/sp-webpart-workbench": "1.12.1",
        "@microsoft/rush-stack-compiler-3.7": "0.2.3",
        "gulp": "~4.0.2",
        "ajv": "~5.2.2",
        "@types/webpack-env": "1.13.1"
    }
}

Here I have named my web part as graph-toolkit-demo.

Now we have to update our code to authenticate to Microsoft Identity to access the Microsoft Graph API. There is no complication and nothing to worry on the authentication or setup, all are taken care by the providers which comes with the package that we installed above. We just need to use the right providers. Since we are using SPFx, we need to use the SharePoint Provider. This can be achieved with just a single line of code which is shown below. Update your <webpart>.ts file with the below code.

import { Providers, SharePointProvider } from '@microsoft/mgt-spfx';
protected async onInit() {
    if (!Providers.globalProvider) {
        Providers.globalProvider = new SharePointProvider(this.context);
    }
}

So with the above code, the authentication is set. Now we can see how we can use the components in our <webpart>.tsx file. Before modifying the web part file, we need to create some folders and files which makes it easy for maintaining the controls and for re-usability.

Create a folder named ToolkitControl in the src folder. Add the following files

  • Graph.Get.tsx
  • controlStyles.module.scss

The style class is common for all the controls and for each control you can create a separate tsx file and implement the business logic.

Update Graph.Get.tsx with the below code

import * as React from 'react';
import { FC } from 'react';
import styles from './controlStyles.module.scss';
import { Get, MgtTemplateProps } from '@microsoft/mgt-react/dist/es6/spfx';

export const GraphGet: FC<{}> = (props) => {

    const LoadingTemplate = (props: MgtTemplateProps) => {
        return (
            <div>Loading...</div>
        );
    };

    const ProfileInfo = (props: MgtTemplateProps) => {
        console.log(props);
        return (
            <div>
                <div><b>Display Name: </b>{props.dataContext.displayName}</div>
                <div><b>Job Title: </b>{props.dataContext.jobTitle}</div>
                <div><b>Email: </b>{props.dataContext.mail}</div>
            </div>
        );
    };

    const MessageTemplate = (props: MgtTemplateProps) => {
        console.log(props);
        return (
            <div>
                <div><b>'{props.dataContext.subject}'</b> from <i>{props.dataContext.sender.emailAddress.name}</i></div>
            </div>
        );
    };

    return (
        <div className={styles.getStyle}>
            <p>My Profile Info</p>
            <Get resource="/me" >
                <LoadingTemplate template="loading" />
                <ProfileInfo template="default" />
            </Get>
            <p>My Email Messages</p>
            <Get resource="/me/messages" pollingRate={5000}>
                <LoadingTemplate template="loading" />
                <MessageTemplate template='value' />
            </Get>
        </div>
    );
};

Below are done in the above code

  • We have imported the correct reference to the Get component from ‘@microsoft/mgt-react/dist/es6/spfx
  • Declared mutiple methods for template
    • LoadingTemplate – This template is loaded while the component is fetching data.
    • ProfileInfo – This template which is used to display the current logged in user profile information.
    • MessageTemplate – This template is used to display the current logged in user’s email messages.
  • Render the Get control with different properties. I have used twice to show you how you can use the control properties and custom styles.
  • For the messages, I have also used the property pollingRate which frequently call the api for the configured interval. In this code, the component will call the api /me/messages for every 5 seconds.

Note: I have declared the template method in the same file. If you think the template is complex and it involves some business rules, then you can also define the template in a separate ts file. The links to the documentation is mentioned in the reference section below.

Update controlStyles.module.scss file

@import '~office-ui-fabric-react/dist/sass/References.scss';

.getStyle {
    color: black;
    p {
        color: black;
        font-size: 15px;
        font-weight: bold;
    }
}

The control is ready and now we can render the control in the actual webpart.tsx file. Update the file with the required import and the control inside the render method.

import { GraphFileList } from '../../../ToolkitControls/Graph.Get';
public render(): React.ReactElement<IGraphToolkitDemoProps> {
    return (
        <div className={styles.graphToolkitDemo}>
            <div className={styles.container}>
                <div className={styles.row}>
                    <div className={styles.column}>
                        <GraphGet />
                    </div>
                </div>
            </div>
        </div>
    );
}

Now the last and the most important for the Graph API to access the data. I think you figured it out, its the scopes. We have to define the scopes that are used by the control in the package-solution.json file.

"webApiPermissionRequests": [
            {
                "resource": "Microsoft Graph",
                "scope": "User.Read.All"
            },
            {
                "resource": "Microsoft Graph",
                "scope": "Mail.Read"
            }
 ]

Thats it. You are done with the coding part and now comes the fun part. Execute the code and see how it renders. Make sure you approve the API requests in the SharePoint Admin Center.

Video

Coming soon…

Reference Links

Happy Coding…

Advertisement

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 )

Twitter picture

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

Facebook photo

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

Connecting to %s