Log in with phone number using Firebase and React

The process to log in a user using Firebase's signInWithPhoneNumber() and React:

  1. User writes the phone number and executes login()
  2. Invisible reCaptcha is created, and user gets verification code
  3. User writes verification code and executes verify()

Let's start with the main component:

jsx
import { auth, RecaptchaVerifier, signInWithPhoneNumber } from './Firebase'

const PhoneLogin = () => {

    const [numb, setNumb] = useState('')
    const [code, setCode] = useState('')
    const [resp, setResp] = useState(null)

    const login  = () => /* Defined in next section */
    const verify = () => /* Defined in next section */

    return(
        <>
            <input placeholder = 'Your number' onChange = {e => setNumb(e.target.value)}/><button onClick = {login}>Accept</button>
            <input placeholder = 'Your code'   onChange = {e => setCode(e.target.value)}/><button onClick = {verify}>Verify</button>
        </>
    )

}

export default PhoneLogin

Here is the login() function:

javascript
const login = async () => {

    window.recaptchaVerifier = new RecaptchaVerifier('login', {'size': 'invisible'}, auth)

    try{

        let response = await signInWithPhoneNumber(auth, number, window.recaptchaVerifier)

        setResp(response)

    }
    catch(e){

        console.log('There was an error')

    }

}

Here is the verify() function:

javascript
const verify = () => {

    try{

        await resp.confirm(code)
        console.log('User is logged in')

    }
    catch(e){

        console.log('There was an error')

    }

}

Note

You can hide the reCaptcha by adding the following CSS lines:

CSS
.grecaptcha-badge {
    display: none !important;
}

Remember that you need to add the following lines to the form to comply with Google's Privacy Policy:

HTML
This site is protected by reCAPTCHA and the <a href = 'https://policies.google.com/privacy'>Google Privacy Policy</a> and <a href = 'https://policies.google.com/terms'>Terms of Service</a> apply.

Hi, I'm Erik, an engineer from Barcelona. If you like the post or have any comments, say hi.