DEV Community

Shivani tiwari
Shivani tiwari

Posted on

Phone Otp login using react Js

Hey Every one 🙋‍♀️

Today I want to share with you Phone OTP login using react

there is some Features which you have to include

  1. Create Project - npx create-react-all projectName
  2. Install react-router-Dom -npm i react-router-dom
  3. install react-icon- npm install react-icons --save
  4. Install Firebase using -npm i react-firebase
  5. react-phone-input-2 - install this package For Input Field
  6. react-otp-input install this package For Input OTP .
  7. react hot toast - install this package For Beautiful Notification

After Install All these let code here

Firebase.config,js

// Import the functions you need from the SDKs you need
import { initializeApp } from "firebase/app";
import { getAuth } from "firebase/auth";
// TODO: Add SDKs for Firebase products that you want to use
// https://firebase.google.com/docs/web/setup#available-libraries

// Your web app's Firebase configuration
const firebaseConfig = {
  apiKey: "AIzaSyDs5ConzFDM2yGvweN-sZdAPFAlowyCDhE",
  authDomain: "reactmoviepp.firebaseapp.com",
  projectId: "reactmoviepp",
  storageBucket: "reactmoviepp.appspot.com",
  messagingSenderId: "719848561957",
  appId: "1:719848561957:web:254facecfb591921474ecc",
};

// Initialize Firebase
const app = initializeApp(firebaseConfig);
export const auth = getAuth(app);
Enter fullscreen mode Exit fullscreen mode

Login.jsx

import React, { useState } from "react";
import Style from "../Auth/login.module.css";
import bgimg from "../Asset/Img/back.jpg";
import { BiSolidPhoneCall } from "react-icons/bi";
import { BsFillShieldLockFill } from "react-icons/bs";
import PhoneInput from "react-phone-input-2";
import "react-phone-input-2/lib/style.css";
import OtpInput from "react-otp-input";
import { auth } from "../firebase.config";
import { RecaptchaVerifier, signInWithPhoneNumber } from "firebase/auth";
import { Toaster, toast } from "react-hot-toast";
const Login = () => {
  const [otp, setOtp] = useState("");
  const [ph, setPh] = useState("");
  const [showOtp, setShowOtp] = useState(false);
  const [loading, setLoading] = useState(false);
  const [user, setUser] = useState(false);

  function onCaptchaVerify() {
    if (!window.RecaptchaVerifier) {
      window.recaptchaVerifier = new RecaptchaVerifier(
        auth,
        "recaptcha-container",
        {
          size: "normal",
          callback: (response) => {
            onSignup();
          },
          "expired-callback": () => {},
        }
      );
    }
  }

  function onSignup(event) {
    event.preventDefault();
    setLoading(true);
    onCaptchaVerify();
    const appVerifier = window.recaptchaVerifier;
    const phoneNumber = "+" + ph;

    signInWithPhoneNumber(auth, phoneNumber, appVerifier)
      .then((confirmationResult) => {
        window.confirmationResult = confirmationResult;
        setLoading(false);
        setShowOtp(true);
        toast.success("OTP Sended Sucessfully");
      })
      .catch((error) => {
        setLoading(false);
        toast.error(error.message);
      });
  }

  function onOtpverify() {
    window.confirmationResult
      .confirm(otp)
      .then(async (result) => {
        // User signed in successfully.
        const user = result.user;
        setUser(user);
        setLoading(false);
      })
      .catch((error) => {
        console.log(error.message);
        toast.error(error.message);
      });
  }

  return (
    <div className={`d-flex justify-content-center`}>
      <Toaster toastOptions={{ duration: 4000 }} />
      <img src={bgimg} alt="bgimg" className={` ${Style.loginimg}`} />
      {!user ? (
        <div className={`row position-absolute mt-5  `}>
          <div className="signuppage mt-5 bg-dark text-white p-5 ">
            {showOtp ? (
              <div className="optvarificationcontent">
                <span className="d-flex justify-content-center">
                  <BsFillShieldLockFill size={40} />
                </span>
                <h6 className="text-center mt-3">Enter Your OTP </h6>
                <OtpInput
                  value={otp}
                  onChange={setOtp}
                  numInputs={6}
                  shouldAutoFocus
                  renderInput={(props) => (
                    <input
                      {...props}
                      style={{
                        width: "30px",
                        marginRight: "12px",
                      }}
                    />
                  )}
                ></OtpInput>
                <div className="d-flex justify-content-center">
                  <button
                    className="btn btn-primary mt-3 w-75 "
                    onClick={onOtpverify}
                  >
                    {loading && (
                      <span
                        className="spinner-border spinner-border-sm"
                        style={{ marginRight: "10px" }}
                      ></span>
                    )}
                    <span> Verify OTP</span>
                  </button>
                </div>
              </div>
            ) : (
              <div>
                <span className="d-flex justify-content-center">
                  <BiSolidPhoneCall size={40} />
                </span>
                <h6 className="text-center mt-3">Verify Your Phone NUmber </h6>
                <PhoneInput
                  country={"in"}
                  value={ph}
                  onChange={setPh}
                ></PhoneInput>
                <div className="d-flex justify-content-center">
                  <button
                    className="btn btn-primary mt-3 w-75 "
                    onClick={onSignup}
                  >
                    {loading && (
                      <span
                        className="spinner-border spinner-border-sm"
                        style={{ marginRight: "10px" }}
                      ></span>
                    )}
                    <span>Send OTP Via SMS</span>
                  </button>
                </div>
                <div id="recaptcha-container" className="mt-6"></div>
              </div>
            )}
          </div>
        </div>
      ) : (
        <div className=" row position-absolute  text-white p-5">
          <p style={{ marginTop: "70%" }}>Login Sucessfully</p>
        </div>
      )}
    </div>
  );
};

export default Login;

Enter fullscreen mode Exit fullscreen mode

I hope you Like this article if you like Appreciate me for more content like this 😃😊

For more Content Check my Instagram - @coders__village

Thank you
ShivaniTiwari

Top comments (0)