Sunday, September 22, 2024
Google search engine
HomeLanguagesReact Hook Form | Create Basic ReactJS Registration and Login Form

React Hook Form | Create Basic ReactJS Registration and Login Form

In ReactJS, creating a form can be a nightmare, but using react-hook-form it can be done smoothly. The library provides all the features that a modern form needs. It is simple, fast, and offers isolated re-renders for elements.

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

Advantage 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

Let’s Start Building Registration Page:

Step 1: Create 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.

Step 3: Start the application using the below commands

npm start
or
yarn start

You will be redirected to your browser.

Step 4: Start Editing UI and Lest 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, 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:

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. See this article for more information on 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 help of key. We use JSON.stringify() convert our object data into a string ( setItem only takes values in the string ) and JSON.parse() to parse 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 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:

Conclusion: We built a basic registration and login page. It could be improved in many ways. In addition to adding validation, UI elements, monitoring particular fields, etc., we can alter many other aspects. It is highly recommended that you read their official document for more detailed information.  

Whether you’re preparing for your first job interview or aiming to upskill in this ever-evolving tech landscape, neveropen Courses are your key to success. We provide top-quality content at affordable prices, all geared towards accelerating your growth in a time-bound manner. Join the millions we’ve already empowered, and we’re here to do the same for you. Don’t miss out – check it out now!

RELATED ARTICLES

Most Popular

Recent Comments