Implement forgot password in ReactJS

In this tutorial, let’s create a reactJS application to implement forgot password with google firebase into reactJS.

Sometimes, while implementing user authentication we often need to implement forgot password functionality to recover a password if the user forgets it.

An email containing some secured password set-up link has been sent to the user’s email. With that link, the user can create a new password.

In this article, we will learn about forgot password implementation with google firebase.

Why google firebase? Well, in a large application we have to rely on some third-party applications and management for security purposes as they are already providing the services for it. There are many service providers, google firebase is one of those.

Steps to implement forgot password in ReactJS

  • Set up the environment with google firebase installation and firebase SDK.
  • Forgot password link
  • Forgot password functionality
  • Create a new password.

Set up the environment with google firebase

  • Install Google firebase in the project directory and add firebase SDK to the file named, firebase.init.js
  • Create a login/registration form.
import React from 'react';
import { useSignInWithEmailAndPassword } from 'react-firebase-hooks/auth';
import { useForm } from "react-hook-form";
import { Link } from 'react-router-dom'
import auth from '../firebase.init';
const Login = () => {

    const { register, handleSubmit, watch, formState: { errors }, reset } = useForm();
    const [
        signInWithEmailAndPassword,
        user,
        loading,
        error,
    ] = useSignInWithEmailAndPassword(auth);
    const onSubmit = data => {
        console.log(data);
        signInWithEmailAndPassword(data.email, data.password)
    };
    if (user) {
        console.log(user)
    };
    if (error) {
        console.log(error)
    };
    return (
        <div className=" flex justify-center lg:min-h-screen items-center">
            <div className="card w-full md:w-96 items-center shadow-2xl bg-base-100">
                <form onSubmit={handleSubmit(onSubmit)} className="card-body w-full lg:w-96">
                    <div className="form-control">
                        <label className="label">
                            <span className="label-text">Email</span>
                        </label>
                        <input
                            type="email" placeholder="email" className="input input-bordered"
                            {...register("email", { required: true })}

                        />
                        <span className="label-text text-error">{errors.email?.type === 'required' && "Email is required"}</span>
                    </div>
                    <div className="form-control">
                        <label className="label">
                            <span className="label-text">Password</span>
                        </label>
                        <input

                            type="password" placeholder="password" className="input input-bordered"
                            {...register("password", { required: true })} />
                        <span className="label-text text-error">{errors.password?.type === 'required' && "Password is required"}</span>


                    </div>
                    <div className="form-control mt-6">
                        <button type="submit" className="btn ">Login</button>
                    </div>

                </form>

                <label className="mt-2">
                    Don't have an account?<Link to="/registration" className="btn btn-link text-white underline px-0">Register</Link>
                </label>
            </div>
        </div>
    );
};

export default Login;

 

  • Install react-hook-form to get the form values (you can get the value in various ways. It doesn’t necessarily require to use of any packages for that. But react-hook-form provides us with more functionalities and methods to apply to the input fields. To know about getting the input values with react-hook-form, Please read this article.
  • Implement registering a user functionality using google firebase and react-firebase-hooks.
  • Make sure the user has been registered successfully

Note: To know in detail about the steps above, Please read this article to know about implementing Login and Registering functionality and follow the steps carefully.

Check GitHub for the source code.

Create Forgot password link

  • Add a Forgot password below the Login Button.
 <h5 className=''>Forgot Password? <span className='btn btn-link underline text-white font-bold'>Send Reset Mail</span></h5>
import React from 'react';
import { useSignInWithEmailAndPassword } from 'react-firebase-hooks/auth';
import { useForm } from "react-hook-form";
import { Link } from 'react-router-dom'
import auth from '../firebase.init';
const Login = () => {

    const { register, handleSubmit, watch, formState: { errors }, reset } = useForm();
    const [
        signInWithEmailAndPassword,
        user,
        loading,
        error,
    ] = useSignInWithEmailAndPassword(auth);
    const onSubmit = data => {
        console.log(data);
        signInWithEmailAndPassword(data.email, data.password)
    };
    if (user) {
        console.log(user)
    };
    if (error) {
        console.log(error)
    };
    return (
        <div className=" flex justify-center lg:min-h-screen items-center">
            <div className="card w-full md:w-96 items-center shadow-2xl bg-base-100">
                <form onSubmit={handleSubmit(onSubmit)} className="card-body w-full lg:w-96">
                    <div className="form-control">
                        <label className="label">
                            <span className="label-text">Email</span>
                        </label>
                        <input
                            type="email" placeholder="email" className="input input-bordered"
                            {...register("email", { required: true })}

                        />
                        <span className="label-text text-error">{errors.email?.type === 'required' && "Email is required"}</span>
                    </div>
                    <div className="form-control">
                        <label className="label">
                            <span className="label-text">Password</span>
                        </label>
                        <input

                            type="password" placeholder="password" className="input input-bordered"
                            {...register("password", { required: true })} />
                        <span className="label-text text-error">{errors.password?.type === 'required' && "Password is required"}</span>


                    </div>
                    <div className="form-control mt-6">
                        <button type="submit" className="btn ">Login</button>
                    </div>

                </form>
                <h5 className=''>Forgot Password? <span className='btn btn-link underline text-white font-bold'>Send Reset Mail</span></h5>

                <label className="mt-2">
                    Don't have an account?<Link to="/registration" className="btn btn-link text-white underline px-0">Register</Link>
                </label>
            </div>
        </div>
    );
};

export default Login;

Note: We are using Tailwind CSS classes for styling. To know more about it, Please read this article.

Forgot password functionality

  • Import below dependencies in the Login component from 'react-firebase-hook'
import { useSignInWithEmailAndPassword, useSendPasswordResetEmail  } from 'react-firebase-hooks/auth';
  • Write the below variable inside the Login component Function.
const [sendPasswordResetEmail, sending, error] = useSendPasswordResetEmail(
auth
);
  • Use watch method from useForm() to get the onChange() values from the email field.
    // get the email value
    const email = watch('email')
  • Create an onCLick() event handler to Forgot password.
<h5 className=''>Forgot Password? <span className='btn btn-link underline text-white font-bold' onClick={handleResetPassword}>Send Reset Mail</span></h5>
  • Create the function for handleResetPassword()
// get the email value
    const email = watch('email')
    // console.log(email)
    const [sendPasswordResetEmail, sending, resetError] = useSendPasswordResetEmail(
        auth
    );
    const handleResetPassword = async () => {
        if (email) {
            alert('success')
            await sendPasswordResetEmail(email);
        }
        else {
            alert('Something went wrong.')
        }
    }

Here, we are using async await so that we can block the functionality for the codes after sendPasswordResetEmail(email), and we are passing the email that we are getting from the watch method of useForm().

import React from 'react';
import { useSignInWithEmailAndPassword, useSendPasswordResetEmail } from 'react-firebase-hooks/auth';
import { useForm } from "react-hook-form";
import { Link } from 'react-router-dom'
import auth from '../firebase.init';
const Login = () => {

    const { register, handleSubmit, watch, formState: { errors }, reset } = useForm();
    const [
        signInWithEmailAndPassword,
        user,
        loading,
        error,
    ] = useSignInWithEmailAndPassword(auth);
    const onSubmit = data => {
        console.log(data);
        signInWithEmailAndPassword(data.email, data.password)
    };
    if (user) {
        console.log(user)
    };
    if (error) {
        console.log(error)
    };
    // get the email value
    const email = watch('email')
    // console.log(email)
    const [sendPasswordResetEmail, sending, resetError] = useSendPasswordResetEmail(
        auth
    );
    const handleResetPassword = async () => {
        if (email) {
            alert('success')
            await sendPasswordResetEmail(email);
        }
        else {
            alert('Something went wrong.')
        }
    }
    return (
        <div className=" flex justify-center lg:min-h-screen items-center">
            <div className="card w-full md:w-96 items-center shadow-2xl bg-base-100">
                <form onSubmit={handleSubmit(onSubmit)} className="card-body w-full lg:w-96">
                    <div className="form-control">
                        <label className="label">
                            <span className="label-text">Email</span>
                        </label>
                        <input
                            type="email" placeholder="email" className="input input-bordered"
                            {...register("email", { required: true })}

                        />
                        <span className="label-text text-error">{errors.email?.type === 'required' && "Email is required"}</span>
                    </div>
                    <div className="form-control">
                        <label className="label">
                            <span className="label-text">Password</span>
                        </label>
                        <input

                            type="password" placeholder="password" className="input input-bordered"
                            {...register("password", { required: true })} />
                        <span className="label-text text-error">{errors.password?.type === 'required' && "Password is required"}</span>


                    </div>
                    <div className="form-control mt-6">
                        <button type="submit" className="btn ">Login</button>
                    </div>

                </form>
                <h5 className=''>Forgot Password? <span className='btn btn-link underline text-white font-bold' onClick={handleResetPassword}>Send Reset Mail</span></h5>

                <label className="mt-2">
                    Don't have an account?<Link to="/registration" className="btn btn-link text-white underline px-0">Register</Link>
                </label>
            </div>
        </div>
    );
};

export default Login;

Create a new password

  • First, create a user with an email address. To know about creating a user, walkthrough to This Article.
  • Fill up the email input field with a valid email (the email that was used to create the user)
  • Now, click on SEND RESET MAIL

  • Check the inbox in the email (Check the spam folder as well)

 

  • Click on the reset link.

There, you can change your password.

This is how we can implement forgot password functionality to a React project.