3
votes

I am trying to implement firebase phone authentication in react js without using the firebase UI. How do I do it?

code

requestVerificationCode = () => {
    const { phoneNumber } = this.state;
    const appVerifier = new firebase.auth.RecaptchaVerifier(
      "recaptcha-container"
    );
    if (phoneNumber < 10) {
      this.setState({ error: true });
    } else {
      this.setState({ message: "Sending code ..." });

      firebase
        .auth()
        .signInWithPhoneNumber(phoneNumber, appVerifier)
        .then(confirmResult =>
          this.setState({ confirmResult, verifying: true })
        )
        .catch(error =>
          this.setState({
            message: `Sign In With Phone Number Error: ${error.message}`
          })
        );
    }
  };

error


auth.esm.js:282 Uncaught K {code: "auth/argument-error", message: "reCAPTCHA container is either not found or already contains inner elements!"}

1
what have you tried so far? - Tobi
what was the error? - Jee Mok
You need to have an element with the ID of recaptcha-container in your html - TheUnreal
Still not working @TheUnreal - jaydee
I don't have enough reputation to comment, but I managed to get the above working by including e.preventDefault(). - dean schmid

1 Answers

4
votes

The important part is to wait for componentDidMount() or mounted() in Vue JS so that the dom element containing "recaptcha-container" is mounted.

HTML

<input id="recaptcha-container" type="button" onClick="this.onClick" />

JS

componentDidMount () {
    window.recaptchaVerifier = new firebase.auth.RecaptchaVerifier("recaptcha-container",
    {
       size:"invisible"
        // other options
    });
}

onClick() {
    const phoneNumber = this.phone;
    const appVerifier = window.recaptchaVerifier;
    firebase
    .auth()
    .signInWithPhoneNumber(phoneNumber, appVerifier)
    .then(confirmResult => {
      // success
    })
    .catch(error => {
      // error
    });
}

If you re-direct the user away from your component where id="recaptcha-container" lives, then recaptcha will work fine but throw a style related error in the console, but that's because it's wants a permanent place on the page.