The process to log in a user using Firebase's signInWithPhoneNumber()
and React:
login()
verify()
Let's start with the main component:
jsximport { 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:
javascriptconst 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:
javascriptconst verify = () => { try{ await resp.confirm(code) console.log('User is logged in') } catch(e){ console.log('There was an error') } }
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:
HTMLThis 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.