User authentication is a critical aspect of many web applications, and phone number authentication has become increasingly popular for its convenience and security. Firebase, a powerful platform developed by Google, offers various authentication methods, including phone number authentication. In this article, we will explore how to authenticate a phone number using Firebase in a ReactJS application.
The following approach covers how to authenticate with a phone number using firebase in react. We have used the firebase module to achieve so.
Creating React Application And Installing Module:
Step 1: Create a React myapp using the following command:
npx create-react-app myapp
Step 2: After creating your project folder i.e. myapp, move to it using the following command:
cd myapp
Project structure: Our project structure will look like this.
Step 3: After creating the ReactJS application, Install the firebase module using the following command:
npm install firebase@8.3.1 --save
Step 4: Go to your firebase dashboard and create a new project and copy your credentials.
const firebaseConfig = { apiKey: "your api key", authDomain: "your credentials", projectId: "your credentials", storageBucket: "your credentials", messagingSenderId: "your credentials", appId: "your credentials" };
Step 5: Initialize the Firebase into your project by creating a firebase.js file with the following code.
Javascript
import firebase from 'firebase' ; Â
const firebaseConfig = { Â Â Â Â // Your credentials }; Â
firebase.initializeApp(firebaseConfig); let auth = firebase.auth(); export { auth, firebase }; |
Step 6: Go to your Firebase dashboard and Enable the phone sign-in method as shown below.
Step 7: Now install the npm package i.e. react-firebase-hooks using the following command.
React-firebase-hooks:
https://www.npmjs.com/package/react-firebase-hooks
npm i react-firebase-hooks
This package helps us to listen to the current state of the user.
Step 8: Create two files i.e. login.js and main.js with the following code.
Javascript
// login.js import React, { useState } from 'react' ; import { firebase, auth } from './firebase' ; Â
const Login = () => {     // Inputs     const [mynumber, setnumber] = useState( "" );     const [otp, setotp] = useState( '' );     const [show, setshow] = useState( false );     const [final, setfinal] = useState( '' ); Â
    // Sent OTP     const signin = () => { Â
        if (mynumber === "" || mynumber.length < 10) return ; Â
        let verify = new firebase.auth.RecaptchaVerifier( 'recaptcha-container' );         auth.signInWithPhoneNumber(mynumber, verify).then((result) => {             setfinal(result);             alert( "code sent" )             setshow( true );         })             . catch ((err) => {                 alert(err);                 window.location.reload()             });     } Â
    // Validate OTP     const ValidateOtp = () => {         if (otp === null || final === null )             return ;         final.confirm(otp).then((result) => {             // success         }). catch ((err) => {             alert( "Wrong code" );         })     } Â
    return (         <div style={{ "marginTop" : "200px" }}>             <center>                 <div style={{ display: !show ? "block" : "none" }}>                     <input value={mynumber} onChange={(e) => {                         setnumber(e.target.value)                     }}                         placeholder= "phone number" />                     <br /><br />                     <div id= "recaptcha-container" ></div>                     <button onClick={signin}>Send OTP</button>                 </div>                 <div style={{ display: show ? "block" : "none" }}>                     <input type= "text" placeholder={ "Enter your OTP" }                         onChange={(e) => { setotp(e.target.value) }}></input>                     <br /><br />                     <button onClick={ValidateOtp}>Verify</button>                 </div>             </center>         </div>     ); } Â
export default Login; |
Javascript
// main.js import React from 'react' ; import { auth } from './firebase' ; Â
const Mainpage = () => { Â
    const logout = () => {         auth.signOut();     } Â
    return (         <div style={{ marginTop: 250 }}>             <center>                 <h3>Welcome {auth.currentUser.phoneNumber}</h3>                 <button style={{ "marginLeft" : "20px" }}                     onClick={logout}>Logout</button>             </center>         </div>     ); } Â
export default Mainpage; |
Step 9: Finally Import all required files in App.js file as shown below.
Javascript
import React from 'react' ; import { auth } from './firebase' ; import { useAuthState } from 'react-firebase-hooks/auth' ; import Login from './login' ; import Mainpage from './main' ; Â
function App() { Â Â Â Â const [user] = useAuthState(auth); Â Â Â Â return ( Â Â Â Â Â Â Â Â user ? <Mainpage /> : <Login /> Â Â Â Â ); } Â
export default App; |
Step to Run Application: Run the application using the following command from the root directory of the project:
npm start
Output: Now open your browser and go to http://localhost:3000/, you will see the following output: