Open In App

Basic Registration and Login Form Using React Hook Form

Improve
Improve
Like Article
Like
Save
Share
Report

In ReactJS, creating a form can be a nightmare as it involves handling inputs and validating inputs. React-hook-form is a ReactJS library that simplifies the process of creating forms.

The library provides all the features that a modern form needs. It is simple, fast, and offers isolated re-renders for elements.

In this article, we will learn how to create a basic registration and login form in React. We will be using the React Hook Form library to complete this task. Let’s look at the features and advantages of the React Hook Form library, and understand why is it used to create forms.

React Hook Form Library

React Hook Form is a popular third-party library that simplifies form management in React functional components using hooks. It provides a comprehensive set of functionalities to handle various aspects of form handling like state management, field handling, form submission, etc.

Features of React Hook Form

  • Open-source
  • Supports TypeScript
  • Provides DevTool for inspecting form data
  • Provides Form Builder – create forms by drag and drop
  • Supports for React-native

Steps to Build Registration and Login Page in React

Below are the steps that you can follow to build your first registration page. We will be building a basic registration and login page in React.

Step 1: Create a React application by using the below commands

npx create-react-app shopping-cart

Step 2: Cd into the project  folder

cd shopping-cart

Project Structure: The project structure will look like the following.

project structure

Step 3: Start the application using the below commands

npm start
or
yarn start

You will be redirected to your browser.

starting application

Step 4: Start Editing the UI and let’s Create a Basic Registration Form. In the src/App.js file, delete all the code, and create your form. In case you don’t know how to build, it’s fine please refer to the below code. 

App.js: Creating a simple react form containing name, email, and password fields.

Filename: App.js

JavaScript
// Inside src/App.js

import React from "react";
import "./App.css";

function App() {
    return (
        <>
            <p className="title">Registration Form</p>

            <form className="App">
                <input type="text" />
                <input type="email" />
                <input type="password" />
                <input type={"submit"}
                    style={{ backgroundColor: "#a1eafb" }} />
            </form>
        </>
    );
}

export default App;

App.css: Contains styles for the App.js component.

Filename: App.css 

CSS
/* Inside src/App.css */

body {
    height: 100vh;
    display: flex;
    justify-content: center;
    align-items: center;
}

.title {
    text-align: center;
    width: 30vw;
    background-color: rgb(190, 164, 214);
    padding: 2vw 1vw;
    border-radius: 10px 10px 0 0;
    font-size: 2rem;
    font-family: Verdana, Geneva, Tahoma, sans-serif;
}

.App {
    text-align: center;
    display: flex;
    flex-direction: column;
    margin: auto;
    width: 30vw;
    padding: 2vw 1vw;
    background-color: rgb(250, 194, 194);
    border-radius: 0 0 10px 10px;
}

input {
    border: 1px solid rgb(172, 171, 171);
    border-radius: 10px;
    padding: 1vw 1vw;
    outline: none;
    margin: 5px;
}

Step 5: Install the react-hook-form library

npm install react-hook-form

Step 6: Import useForm hook from react-hook-form. It will return your register, handlesubmit, and errors methods

  • register: This is used to handle input fields. We can access the input field later using the name given to it. In the above example, that is “firstname”.
<input {...register("firstname")} />
  •  handlesubmit: Is used to handle the form submission. It takes a custom method ( eg: onSubmit ). It will automatically collect field values.
const onSubmit = data =>  console.log(data);

<form onSubmit={handleSubmit(onSubmit)}>
// input field 1
// input field 2
<input type="submit" />
</form>
  • errors:  We use this to handle errors. if we leave “firstname” field empty it will set errors.first name =  true
<input {...register("firstname", { required: true })} />
{errors.firstname && <span>This field is required</span>}

Let’s use all concepts and create a form. Adding the register method to each input field and giving a name. Also handling form submission

Filename: App.js

JavaScript
// inside src/App.js
// Replace previous code with this.

import React from "react";
import { useForm } from "react-hook-form";
import "./App.css";

function App() {
    const { register, handleSubmit, formState: { errors } } = useForm();

    const onSubmit = (data) => console.log(data);

    return (
        <>
            <p className="title">Registration Form</p>

            <form className="App" onSubmit={handleSubmit(onSubmit)}>
                <input type="text" {...register("name")} />
                <input type="email" {...register("email", { required: true })} />
                {errors.email && <span style={{ color: "red" }}>
                    *Email* is mandatory </span>}
                <input type="password" {...register("password")} />
                <input type={"submit"} style={{ backgroundColor: "#a1eafb" }} />
            </form>
        </>
    );
}
export default App;

Output:

registration form created

Step 7: Storing values in localStorage: As we are building a login form, we need to verify log-in credentials so we store the form data in local storage.

const onSubmit = (data) => {
localStorage.setItem(data.email, JSON.stringify({
name: data.name, password: data.password
}));
console.log(JSON.parse(localStorage.getItem(data.email)));
};

localStorage provides setItem methods to store whatever we want in the form of key-value pairs of string. And getItem to fetch the stored data back with the help of a key. We use JSON.stringify() converts our object data into a string ( setItem only takes values in the string ) and JSON.parse() parses the string data into an object.

Building login Page: Create a new file called Login.jsx in the src folder and add the below code. We copied the code from the registration page and removed the name field from it. We changed the onsubmit method code as well. 

Filename: Login.jsx 

JavaScript
// inside src/Login.jsx

import React from "react";
import { useForm } from "react-hook-form";
import "./App.css";

function Login() {
    const {
        register,
        handleSubmit,
        formState: { errors },
    } = useForm();

    const onSubmit = (data) => {
        const userData = JSON.parse(localStorage.getItem(data.email));
        if (userData) { // getItem can return actual value or null
            if (userData.password === data.password) {
                console.log(userData.name + " You Are Successfully Logged In");
            } else {
                console.log("Email or Password is not matching with our record");
            }
        } else {
            console.log("Email or Password is not matching with our record");
        }
    };
    return (
        <>
            <p className="title">Login Form</p>

            <form className="App" onSubmit={handleSubmit(onSubmit)}>
                <input type="email" {...register("email", { required: true })} />
                {errors.email && <span style={{ color: "red" }}>
                    *Email* is mandatory </span>}
                <input type="password" {...register("password")} />
                <input type={"submit"} style={{ backgroundColor: "#a1eafb" }} />
            </form>
        </>
    );
}
export default Login;

Output:

registration and login form created

Advantages of using React Hook Form:

  • Easy to learn and build
  • Provides form validation
  • Easy to handle the form submission.
  • We can watch any particular form field.
  • We can integrate with any UI library.
  • Provides schema validation

Conclusion

We built a basic React registration and login page. It can be improved in many ways according to developer preference. In addition to adding validation, UI elements, monitoring particular fields, etc., we can alter many other aspects.



Last Updated : 18 Mar, 2024
Like Article
Save Article
Previous
Next
Share your thoughts in the comments
Similar Reads