React Application Integration To Microsoft Graph Using Microsoft Graph SDK

Introduction

Nowadays, Microsoft 365, previously known as O365, is used by millions of people all over the world to communicate and collaborate on corporate data or records with an extreme level of security. Records are encrypted and stored in Microsoft 365 and it is a very highly extendable platform that can connect to any independent application without compromising the security. Many organizations are demanding content, records, and analytics views from Microsoft 365 in separate applications.

Learning Objectives

At the end of the article, you will: 

  1. Brief understanding of Microsoft Graph
  2. Brief Understanding of Microsoft Graph SDK
  3. Create React Application using Node js
  4. Register Application in Azure 
  5. Integrate Microsoft Graph SDK to React
  6. Display Sample Records in React application in local Host
  7. Conclusion

Prerequisites

  1. Microsoft 365 Environment
  2. Azure Environment
  3. Node JS
  4. Visual Studio Code

Let us begin.

What is Microsoft Graph and what its usefulness

Microsoft Graph is a platform, where developers can connect and extend data that is stored in different services which are part of Microsoft 365.

It is built on top of M365 and allows developers to communicate their services with Azure AD, Teams, Outlook, SharePoint, and many more.

Developers can build smarter apps using Microsoft graph using Microsoft 365 applications. It is giving you a single REST API endpoint that will connect all M365 Applications.

Using Graph API endpoint, accessing data is very straightforward and transparend for programmers. Developers can build applications to display outlook calendar, upcoming meetings
and find out when the manager or reporting authority is out of office.

Users can also create an application to send alert notifications when anyone is spending much time in meetings or in chatting and getting very frequent documents for users.

What is Microsoft Graph SDK?

Microsoft Graph Software development kit enabled you to create high-quality, efficient applications that can access M365 through Microsoft Graph API.

It includes 2 components,

  1. A Service Library and
  2. A Core Library.

Currently, all major platforms are supported to Microsoft Graph SDK like Android, Angular, React, IOS, JavaScript, Java, and so on.

Create React Application using Node

Step 1

Open Node command Prompt.

Step 2

Run the below command to your desire physical location on your hard drive.

npx create-react-app m365integration--template typescript --use-npm

Note
Capital letters are allowed in the application name. 

Once, the command is successfully run then you will get output as below,

React Application Integration to Microsoft Graph using Microsoft Graph SDK

Step 3

Change working directory to directory which is newly created with this app,

cd m365integration

Step 4

Now, time to install Graph SDK React Component in the Application. To install Microsoft Graph SDK React Component, Run the below command.

npm i @microsoft/mgt-react

It includes a number of inbuilt components like file, file list, login, people, people picker, Person, Person card, and so on..

Step 5

To communicate with Microsoft Graph, Authentication is mandatory. Install below packages that are responsible for MSAL 2.0 auth Provider. 

npm i @microsoft/mgt-element @microsoft/mgt-msal2-provider

Step 6

Let's confirm that your application can run properly.

npm start

React Application Integration to Microsoft Graph using Microsoft Graph SDK

Application Registration in Azure AD

Microsoft Graph API, which is used to connect the M365 Application, is secured with OAuth 2.0. To connect M365 Apps, you need to register service application in the azure active directory and grant this app to access specific resources like directory, SharePoint Site, or Teams artifacts.

To create the app in Azure Active Directory,

  • Login to Azure portal 
  • Select Azure Active Directory.
  • Select App registrations.
  • Click the New registration button.
  • Enter the name “m365integration” for this app
  • Select Accounts in any organizational directory in the type of account
  • Select Single Page Application (SPA) in the redirect URL field 
  • Enter http://localhost:3000 in URL Field 
  • Click the Register button to save all changes
  • Copy application ID from created application in Azure Active directory, You will get it from the overview tab.

Integrate Microsoft Graph SDK to React

We need to import a couple of packages for authentical providers and initialize MsalProvider in the Application.

Add the below code in file "src/index.tsx".

import React from 'react';
import ReactDOM from 'react-dom';
import './index.css';
import App from './App';
import reportWebVitals from './reportWebVitals';
import { Providers } from '@microsoft/mgt-element';
import { Msal2Provider } from '@microsoft/mgt-msal2-provider';
Providers.globalProvider = new Msal2Provider({
  clientId: '<Azure AD Application ID>' // Add your application ID which is registered in Azure
});
ReactDOM.render(
  <React.StrictMode>
    <App />
  </React.StrictMode>,
  document.getElementById('root')
);
reportWebVitals();

Let us add the Login component.

Add below code in file "src/App.tsx".

import React from 'react';
import logo from './logo.svg';
import './App.css';
import { Login } from '@microsoft/mgt-react'; // import login component
function App() {
  return (
    <div className="App">
      <header>
        <Login /> // Use login component
      </header>
    </div>
  );
}
export default App;

Let's run the application.

npm start

The output will be as below,

React Application Integration to Microsoft Graph using Microsoft Graph SDK

Let's add a person component in React Application.

Install the below npm package in Application,

import { Providers, ProviderState } from '@microsoft/mgt';

Update file "src/App.tsx" with below code.

import React, { useState, useEffect } from 'react';
import { Providers, ProviderState } from '@microsoft/mgt';
import logo from './logo.svg';
import './App.css';
import { Login } from '@microsoft/mgt-react';
import { Person } from '@microsoft/mgt-react';
function useIsSignedIn(): [boolean] {
  const [isSignedIn, setIsSignedIn] = useState(false);
  useEffect(() => {
    const updateState = () => {
      const provider = Providers.globalProvider;
      setIsSignedIn(provider && provider.state === ProviderState.SignedIn);
    };

    Providers.onProviderUpdated(updateState);
    updateState();

    return () => {
      Providers.removeProviderUpdatedListener(updateState);
    }
  }, []);

  return [isSignedIn];
}
function App() {
  const [isSignedIn] = useIsSignedIn();
  const [people, setPeople] = useState([]);

  const handleSelectionChanged = (e: any) => {
    setPeople(e.target.selectedPeople);
  };
  return (
    <div className="App">
      <header>
        <Login />
      </header>
      {isSignedIn &&    // Checking if user is signed in that below HTML will be rendered
        <div>
          <div>
            <p>Person Component : <Person personQuery="me"></Person></p>
          </div>
        </div>}
    </div>
  );
}
export default App;

Let us add People Picker and People Component.

Open file "src/App.tsx" and import the below package on the top section of the file.

import { PeoplePicker, People } from '@microsoft/mgt-react';

Update App() function with below code,

function App() {
  const [isSignedIn] = useIsSignedIn();
  const [people, setPeople] = useState([]);

  const handleSelectionChanged = (e: any) => {
    setPeople(e.target.selectedPeople);
  };
  return (
    <div className="App">
      <header>
        <Login />
      </header>
      {isSignedIn &&
        <div>
          <div>
            <p>Person Component : <Person personQuery="me"></Person></p>
          </div>
          <div style={{ width: "400px" }}>
            <p>People Picker Component : <PeoplePicker selectionChanged={handleSelectionChanged} /></p>
            <p>People Component: <People people={people} /></p>
          </div>
        </div>}
    </div>
  );
}

Let's run the application again.

npm Start

The output will be as below,

React Application Integration to Microsoft Graph using Microsoft Graph SDK

Conclusion

In this article, we learned how to integrate React App with Microsoft Graph and how to implement the Microsoft Graph SDK component in React Application.

I hope you enjoyed this article.


Similar Articles