3

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;
Justin XL
  • 38,763
  • 7
  • 88
  • 133

1 Answers1

3

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;
Nikola Metulev
  • 566
  • 3
  • 7
  • I have the same issue. Can you please check this question https://stackoverflow.com/questions/62172912/microsoft-graph-toolkit-component-mgt-login-event-is-not-called-in-react-app-wit – parag patel Jun 03 '20 at 12:32