LoginSignup
6
1

More than 3 years have passed since last update.

"Error: Could not find the FirebaseUI widget element on the page." の対策。

Last updated at Posted at 2020-01-28

経緯

  • React と Firebase でウェブアプリ開発中
  • FirebaseUI を使ってログイン機能を実装したい
  • 以下のエラーが発生
Error: Could not find the FirebaseUI widget element on the page.

ログインページの URL でページを更新するとエラーは出ないのに、React Router で他のページからログインページに飛んでくるとエラーが発生します。。

問題のコード

公式サイトに載っているのとほぼ同じ内容のコードです。
エラーでは ui.start('#firebaseui-auth-container', uiConfig); で指定している要素が見つからないと言っているようです。

import React from 'react';
import firebase from "firebase/app";
import * as firebaseui from "firebaseui";

export default function TestComponent() {
  const ui = firebaseui.auth.AuthUI.getInstance() || new firebaseui.auth.AuthUI(firebase.auth());
  const uiConfig = {
    callbacks: {
      signInSuccessWithAuthResult: function (authResult, redirectUrl) {
        return true;
      },
      uiShown: function () {
        document.getElementById('loader').style.display = 'none';
      }
    },
    signInFlow: 'popup',
    signInSuccessUrl: 'mypage',
      signInOptions: [
        firebase.auth.GoogleAuthProvider.PROVIDER_ID,
      ],
    };

  ui.start('#firebaseui-auth-container', uiConfig);

  return (
    <>
      <div id="firebaseui-auth-container"></div>
      <div id="loader">Loading...</div>
    </>
  );
}

解決策

エラーの内容から <div id="firebaseui-auth-container"></div> がレンダリングされる前に ui.start('#firebaseui-auth-container', uiConfig); が実行されているようなので、レンダリング後に実行させるように useEffect を使います。

import React, { useEffect } from 'react';
import firebase from "firebase/app";
import * as firebaseui from "firebaseui";

export default function TestComponent() {
  useEffect(() => {
    const ui = firebaseui.auth.AuthUI.getInstance() || new firebaseui.auth.AuthUI(firebase.auth());
    const uiConfig = {
      callbacks: {
        signInSuccessWithAuthResult: function (authResult, redirectUrl) {
          return true;
        },
        uiShown: function () {
          document.getElementById('loader').style.display = 'none';
        }
      },
      signInFlow: 'popup',
      signInSuccessUrl: 'mypage',
      signInOptions: [
        firebase.auth.GoogleAuthProvider.PROVIDER_ID,
      ],
    };
    ui.start('#firebaseui-auth-container', uiConfig);
  });

  return (
    <>
      <div id="firebaseui-auth-container"></div>
      <div id="loader">Loading...</div>
    </>
  );
}
6
1
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
6
1