Skip to content
geeksforgeeks
  • Courses
    • DSA to Development
    • Get IBM Certification
    • Newly Launched!
      • Master Django Framework
      • Become AWS Certified
    • For Working Professionals
      • Interview 101: DSA & System Design
      • Data Science Training Program
      • JAVA Backend Development (Live)
      • DevOps Engineering (LIVE)
      • Data Structures & Algorithms in Python
    • For Students
      • Placement Preparation Course
      • Data Science (Live)
      • Data Structure & Algorithm-Self Paced (C++/JAVA)
      • Master Competitive Programming (Live)
      • Full Stack Development with React & Node JS (Live)
    • Full Stack Development
    • Data Science Program
    • All Courses
  • Tutorials
    • Data Structures & Algorithms
    • ML & Data Science
    • Interview Corner
    • Programming Languages
    • Web Development
    • CS Subjects
    • DevOps And Linux
    • School Learning
  • Practice
    • Build your AI Agent
    • GfG 160
    • Problem of the Day
    • Practice Coding Problems
    • GfG SDE Sheet
  • Contests
    • Accenture Hackathon (Ending Soon!)
    • GfG Weekly [Rated Contest]
    • Job-A-Thon Hiring Challenge
    • All Contests and Events
  • React Tutorial
  • React Exercise
  • React Basic Concepts
  • React Components
  • React Props
  • React Hooks
  • React Router
  • React Advanced
  • React Examples
  • React Interview Questions
  • React Projects
  • Next.js Tutorial
  • React Bootstrap
  • React Material UI
  • React Ant Design
  • React Desktop
  • React Rebass
  • React Blueprint
  • JavaScript
  • Web Technology
Open In App
Next Article:
How to Develop User Registration Form in React JS ?
Next article icon

Basic Registration and Login Form Using React Hook Form

Last Updated : 09 Jan, 2025
Comments
Improve
Suggest changes
Like Article
Like
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. Creating registration and login forms is essential for user management. 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:

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:

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.



Next Article
How to Develop User Registration Form in React JS ?
author
mohans8050
Improve
Article Tags :
  • Geeks Premier League
  • ReactJS
  • Web Technologies
  • Geeks-Premier-League-2022

Similar Reads

  • How to Implement Email Registration and Login using Firebase in React?
    Implementing Email Registration and Login using Firebase in React allows us to authenticate the users securely. Firebase provides predefined ways to register users and handle authentication. Firebase offers multiple authentication methods like Email-Password, Google, Facebook, etc. ApproachTo implem
    4 min read
  • How to Develop User Registration Form in React JS ?
    The Form is usually defined inside the <form> tag in conventional HTML code and also in ReactJS. It can have the usual form submission behavior that can take it to a new page but that will not make use of React's full potential, instead, as we all know it is done using React components. Prereq
    3 min read
  • How to Create Form Builder using React and Dynamic State Management ?
    In web development building forms is a common task. However, creating dynamic forms with varying fields and configurations can be a challenge. This is where a form builder tool comes in handy. In this article, we'll learn how to build a form builder tool using React Hooks for state management, allow
    3 min read
  • How to pass data into table from a form using React Components ?
    React JS is a front-end library used to build UI components. This article will help to learn to pass data into a table from a form using React Components. This will be done using two React components named Table and Form. We will enter data into a form, which will be displayed in the table on 'submi
    3 min read
  • ReactJS Form Validation using Formik and Yup
    ReactJS Form Validation using Formik and Yup packages is one good approach for form validation. we can validate forms using controlled components. But it may be time-consuming and the length of the code may increase if we need forms at many places on our website. Formik is designed to manage forms w
    3 min read
  • Create Form Layouts using React and Tailwind CSS
    We will create a responsive form layout using React and Tailwind CSS. We will design the form with input fields, buttons, and icons to create a modern UI. This form layout can be used in various applications such as login pages sign-up forms and contact forms. Forms are essential components of web a
    4 min read
  • How to build a Tic-Tac-Toe Game using React Hooks ?
    To build a Tic-Tac-Toe using react Hooks include the interactive components that represent the board, the signs, and at last the winner of the game. Preview of final output: Let us have a look at how the final application will look like. Prerequisite of Tic-Tac-Toe Game:Introduction to ReactFunction
    8 min read
  • How to log-out user from app using ReactJS ?
    The objective of this article is to how we can set up, log out a user, and retrieve data from local memory User Browser storage in the React app. During the sign-in session, we will save the user details to the browser's local storage, and also during the time of logout, we will remove the user's de
    3 min read
  • Contact Us Form Using ReactJS and Tailwind
    A Contact Us Form is an integral part of an organization's website. It helps the users to reach out to the organization team and share their views. A Contact Form can be used for various purposes such as giving a suggestion, asking queries, and giving feedback. The final feature will look like this:
    4 min read
  • How to Create a Basic Notes App using ReactJS ?
    Creating a basic notes app using React JS is a better way to learn how to manage state, handle user input, and render components dynamically. In this article, we are going to learn how to create a basic notes app using React JS. A notes app is a digital application that allows users to create, manag
    4 min read
geeksforgeeks-footer-logo
Corporate & Communications Address:
A-143, 7th Floor, Sovereign Corporate Tower, Sector- 136, Noida, Uttar Pradesh (201305)
Registered Address:
K 061, Tower K, Gulshan Vivante Apartment, Sector 137, Noida, Gautam Buddh Nagar, Uttar Pradesh, 201305
GFG App on Play Store GFG App on App Store
Advertise with us
  • Company
  • About Us
  • Legal
  • Privacy Policy
  • In Media
  • Contact Us
  • Advertise with us
  • GFG Corporate Solution
  • Placement Training Program
  • Languages
  • Python
  • Java
  • C++
  • PHP
  • GoLang
  • SQL
  • R Language
  • Android Tutorial
  • Tutorials Archive
  • DSA
  • Data Structures
  • Algorithms
  • DSA for Beginners
  • Basic DSA Problems
  • DSA Roadmap
  • Top 100 DSA Interview Problems
  • DSA Roadmap by Sandeep Jain
  • All Cheat Sheets
  • Data Science & ML
  • Data Science With Python
  • Data Science For Beginner
  • Machine Learning
  • ML Maths
  • Data Visualisation
  • Pandas
  • NumPy
  • NLP
  • Deep Learning
  • Web Technologies
  • HTML
  • CSS
  • JavaScript
  • TypeScript
  • ReactJS
  • NextJS
  • Bootstrap
  • Web Design
  • Python Tutorial
  • Python Programming Examples
  • Python Projects
  • Python Tkinter
  • Python Web Scraping
  • OpenCV Tutorial
  • Python Interview Question
  • Django
  • Computer Science
  • Operating Systems
  • Computer Network
  • Database Management System
  • Software Engineering
  • Digital Logic Design
  • Engineering Maths
  • Software Development
  • Software Testing
  • DevOps
  • Git
  • Linux
  • AWS
  • Docker
  • Kubernetes
  • Azure
  • GCP
  • DevOps Roadmap
  • System Design
  • High Level Design
  • Low Level Design
  • UML Diagrams
  • Interview Guide
  • Design Patterns
  • OOAD
  • System Design Bootcamp
  • Interview Questions
  • Inteview Preparation
  • Competitive Programming
  • Top DS or Algo for CP
  • Company-Wise Recruitment Process
  • Company-Wise Preparation
  • Aptitude Preparation
  • Puzzles
  • School Subjects
  • Mathematics
  • Physics
  • Chemistry
  • Biology
  • Social Science
  • English Grammar
  • Commerce
  • World GK
  • GeeksforGeeks Videos
  • DSA
  • Python
  • Java
  • C++
  • Web Development
  • Data Science
  • CS Subjects
@GeeksforGeeks, Sanchhaya Education Private Limited, All rights reserved
We use cookies to ensure you have the best browsing experience on our website. By using our site, you acknowledge that you have read and understood our Cookie Policy & Privacy Policy
Lightbox
Improvement
Suggest Changes
Help us improve. Share your suggestions to enhance the article. Contribute your expertise and make a difference in the GeeksforGeeks portal.
geeksforgeeks-suggest-icon
Create Improvement
Enhance the article with your expertise. Contribute to the GeeksforGeeks community and help create better learning resources for all.
geeksforgeeks-improvement-icon
Suggest Changes
min 4 words, max Words Limit:1000

Thank You!

Your suggestions are valuable to us.

What kind of Experience do you want to share?

Interview Experiences
Admission Experiences
Career Journeys
Work Experiences
Campus Experiences
Competitive Exam Experiences