If you are trying to add FirebaseUI to a webpage in 2023, you might come across the exception:
Uncaught Error: Could not find the FirebaseUI widget element on the page.
The FirebaseUI library promises a single, no-frills way of seamlessly adding the Firebase login flow to your web app. You simply add the FirebaseUI widget to your component and call it a day.
If you are following the documentation, your component might look something like this:
function SignIn() {
ui.start("#firebaseui-login-container", getAuthConfig());
return (
<header className="App-header">
<p> Please sign in</p>
<div id="firebaseui-login-container"></div>
</header>
);
}
export default SignIn;
The problem is that the ui.start
statement has been called before the <div id="firebaseui-login-container"></div>
has. So it is trying to start something on a DOM element that does not exist. The fix to this is to wait until the div has been rendered before starting the ui.
The guidelines tell you to use FirebaseUi-React package , but unfortunately, it only supports React 17.
I want to show you a good workaround, with no frills. The idea is to wrap the ui.start
statement in a UseEffect. It will wait until the FirebaseUI widget div has been rendered to replace it with the form.
Using the useEffect hook
The code would look something like this in a functional component:
function SignInComponent() {
useEffect(() => {
ui.start("#firebaseui-login-container", AuthConfig);
}, []);
return (
<header className="App-header">
<p> Please sign in</p>
<div id="firebaseui-login-container"></div>
</header>
);
}
export default SignIn;
Complete code example
The completed code for a page would look something like this:
// imports ommited for brevity
// Initialize Firebase
const firebaseConfig = {
apiKey: "",
authDomain: "",
projectId: "",
storageBucket: "",
messagingSenderId: "",
appId: "",
measurementId: "",
}
initializeApp(firebaseConfig);
var firebaseui = require("firebaseui");
const auth = getAuth();
const ui = new firebaseui.auth.AuthUI(auth);
const AuthConfig = {
signInOptions: [EmailAuthProvider.PROVIDER_ID],
signInSuccessUrl: "/app",
};
function SignIn() {
useEffect(() => {
ui.start("#firebaseui-login-container", AuthConfig);
}, []);
return (
<header className="App-header">
<p> Please sign in</p>
<div id="firebaseui-login-container"></div>
</header>
);
}
export default SignIn;
This component could be mounted using a button click or some routing logic.
Note that the official documentation for firebaseUI omits the useEffect snippet.
It is rather unfortunate that the firebaseUI-react library has been abandoned for more than one year already. Hopefully, this guide will give a workaround to using firebase in your project.
Let me know if this helped you, and what your project is about!
Leave a Reply