Search code examples
reactjsweb-componentmicrosoft-graph-toolkit

Event handlers of Microsoft Graph Toolkit components not called in React app


I am trying to use the login component from the Microsoft Graph Toolkit in my React app. It works fine, but I cannot seem to be able to make any of the events fire. For example -

import React from "react";
import { MgtLogin, Providers, MsalProvider } from "@microsoft/mgt";
import "./App.css";

Providers.globalProvider = new MsalProvider({
  clientId: "a974dfa0-9f57-49b9-95db-90f04ce2111a"
});

function handleLogin() {
  console.log("login completed");
}

function App() {
  return (
    <div className="App">
      <header className="App-header">
        <mgt-login loginCompleted={handleLogin} />
      </header>
    </div>
  );
}

export default App;

handleLogin is never called.

Update

Here's how it works with hooks.

import React, { useEffect, useRef } from "react";
import { Providers, MsalProvider, LoginType } from "@microsoft/mgt";
import "./App.css";

Providers.globalProvider = new MsalProvider({
  clientId: "a974dfa0-9f57-49b9-95db-90f04ce2111a",
  loginType: LoginType.Popup
});

function App() {
  const loginComponent = useRef(null);

  useEffect(() => {
    console.log("loginComponent", loginComponent);
    loginComponent.current.addEventListener("loginCompleted", () =>
      console.log("Logged in!")
    );
  }, []);

  return (
    <div className="App">
      <header className="App-header">
        <mgt-login ref={loginComponent} />
      </header>
    </div>
  );
}

export default App;

Solution

  • Because React implements its own synthetic event system, it cannot listen for DOM events coming from Custom Elements without the use of a workaround. You need to reference the toolkit components using a ref and manually attach event listeners with addEventListener.

    import React, { Component } from 'react';
    import { MgtLogin, Providers, MsalProvider } from "@microsoft/mgt";
    import "./App.css";
    
    class App extends Component {
    
        constructor(){
            super();
            Providers.globalProvider = new MsalProvider({
                clientId: "a974dfa0-9f57-49b9-95db-90f04ce2111a"
            });
        }
    
        render() {
            return (
                <div className="App">
                    <header className="App-header">
                        <mgt-login ref="loginComponent" />
                    </header>
                </div>
            );
        }
    
        handleLogin() {
            console.log("login completed");
        }
    
        componentDidMount() {
            this.refs.loginComponent.addEventListener('loginCompleted', this.handleLogin);
        }
    }
    
    export default App;