This website uses cookies to ensure you get the best experience on our website.

Skip to content
LOGO
  • Company

    About IGNEK

    Learn about our story and our mission.

    Careers

    We're hiring!

    We always looking for talented peoples. Join our team!

    Blogs

    The latest industry news, updates and info.

    Case Studies

    Take a closer look at the projects we've delivered

    Webinar

    Watch our latest organized webinar

    Get in touch with our HR team

    • hr@ignek.com
    • +91 93284 95160
    • Ahmedabad, Gujarat, India – 382470
  • Services

    Enterprise Portal Development

    Custom Enterprise Portal Development for flawless Solutions

    Dedicated Development Team

    Expand Teams, Optimize Development with Our Expertise

    Back-end Development

    Empowering your digital presence with robust backend development expertise

    Front-end Development

    Crafting engaging user experiences through expert frontend development

    Digital Transformation

    Embrace digital transformation by modernizing process

    SaaS Development

    Transform your business with SaaS Innovative Solutions

    Technologies

    Liferay Services

    Development & Customization

    Theme

    Upgradation

    Migration

    Proof of Concept

    Performance Tunning

    Architecture

    Support & Maintenance

    E-commerce

    Expert Advice

    React Services

    Enterprise Development

    Custom Application

    Single Page Application

    Architecture

    API Integration

    Migration

    Consulting

    Maintenance & Support

    Spring Boot Services

    Web Service

    MVC Web Development

    API Integration

    Security

    Migration

    Microservices

    Support & Maintenance

    AEM Services

    Consulting Service

    Site Development

    Migration & Upgradation

    Integration

    Maintenance & Support

    Custom Solutions

    Content Management

    Team Augementation

  • Solution

    Ready for digital excellence

    In our rapidly evolving world, businesses are always on the lookout for fresh ways to improve their operations and connect with their audiences.

    Contact US

    Solutions

    SaaS : Software As A Service

    Transforming industries through cutting edge SaaS solutions.

    Customer Portal : Boost Business Productivity

    Streamline operations and enhance productivity with our Customer Portal solution.

    Liferay Based Intranet Portal

    Internal portal for company communication, collaboration and resources

    Integration

    Matomo Integration with Liferay

    Integrate Matomo to enable user interactions seamlessly.

    Microsoft Teams integration with Liferay

    Integrate to enable seamless collaboration, messaging within your portal.

    Jira Integration With Liferay

    Optimizes business operations by integrating with Jira.

  • Hire Us

    Liferay

    Get expert Liferay developers for seamless portal solutions.

    React JS

    Get expert ReactJS developers for dynamic web solutions.

    Web Developer

    Get custom web solutions from IGNEK's expert developers.

    Spring Boot

    Get top-notch Spring Boot developers for your project success!

    Healthcare

    Get top Healthcare Developers for cutting-edge medical software.

    MERN Stack

    Get expert MERN developers from IGNEK for custom, innovative project solutions.

    Why Hire Developers From IGNEK ?

    • Certified Developer
    • Transparent Communication
    • Flexible Hiring Modals
    • Fully Signed NDA
    • Cost Effective
    • Easy Exit Policy

    Get in touch with our Sales team

    • sales@ignek.com
    • +91 6351576580
    • info@ignek.com
    • Ahmedabad, Gujarat, India – 382470
SCHEDULE CALL
  • COMPANY
    • About
    • Case Studies
    • Blogs
    • Career
    • Webinar
  • SERVICES
    • Enterprise Portal Development
    • Dedicated Development Team
    • Back-end Development
    • Front-end Development
    • Digital Transformation
    • SaaS Development
  • SOLUTION
    • Customer Portal:  Boost Business Productivity
    • SaaS : Software as a Service
    • Liferay Based Employee Intranet Portal
  • TECHNOLOGY
    • Liferay Services
      • Liferay Development and Customization
      • Liferay Theme Development Service
      • Liferay DXP 7.4 Upgrade
      • Liferay Migration
      • Liferay Proof Of Concept
      • Liferay Performance Tuning
      • Liferay Architecture Design Service
      • Liferay Support And Maintenance Service
      • Liferay Ecommerce Development
      • Liferay Expert Advice
    • ReactJS Services
      • ReactJS Enterprise Application Development
      • ReactJS Custom Application Development
      • ReactJS Single Page Application Development (SPA)
      • ReactJS Applications Architecture
      • ReactJS API Integration
      • ReactJS Migration
      • ReactJS Consulting
      • ReactJS Maintenance and Support
    • Spring Boot Services
      • Spring Boot Web Development Service
      • Spring MVC Web Development
      • Spring Boot API Integration Service
      • Spring Boot Security
      • Spring Boot Migration Service
      • Spring Boot Microservices
      • Spring Boot Support & Maintenance Service
    • AEM Development Services
      • AEM Consulting Services
      • AEM Site Development
      • AEM Migration & Upgradation
      • AEM Integration Services
      • AEM Maintenance & Support
      • AEM Content Management
      • Custom AEM Solutions
      • AEM Team Augmentation
  • INTEGRATION
  • HIRE US
    • Hire Liferay Developer
    • Hire ReactJS Developer
    • Hire Spring Boot Developer
    • Hire Healthcare Developer
    • Hire Web Developer
    • Hire MERN Stack Developer
  • CONTACT US
  • Company

    About IGNEK

    Careers

    We're hiring!

    Blogs

    Case Studies

    Webinar

    Get in touch with our HR team

    • hr@ignek.com
    • +91 93284 95160
    • Ahmedabad, Gujarat, India – 382470
  • Services

    Enterprise Portal Development

    Dedicated Development Team

    Back-end Development

    Front-end Development

    Digital Transformation

    SaaS Development

    Technologies

    Liferay Liferay Services
    • Development & Customization
    • Theme
    • Upgradation
    • Migration
    • Proof of Concept
    • Performance Tuning
    • Architecture
    • Support & Maintenance
    • E-commerce
    • Expert Advice
    React React Services
    • Enterprise Development
    • Custom Application
    • Single Page Application
    • Architecture
    • API Integration
    • Migration
    • Consulting
    • Maintenance & Support
    Spring Boot Spring Boot Services
    • Web Service
    • MVC Web Development
    • API Integration
    • Security
    • Migration
    • Microservices
    • Support & Maintenance
    AEM AEM Services
    • Consulting Service
    • Site Development
    • Migration & Upgradation
    • Integration
    • Maintenance & Support
    • Custom Solutions
    • Content Management
    • Team Augmentation
  • Solution

    Ready for digital excellence

    In our rapidly evolving world, businesses are always on the lookout for fresh ways to improve their operations and connect with their audiences.

    Contact US

    Solutions

    SaaS : Software As A Service

    Customer Portal : Boost Business Productivity

    Liferay Based Intranet Portal

    Integration

    Matomo Integration with Liferay

    Microsoft Teams integration with Liferay

    Jira Integration With Liferay

  • Hire Us

    Liferay

    React JS

    Web Developer

    Spring Boot

    Healthcare

    MERN Stack

    Why Hire Developers From IGNEK ?

    • Certified Developer
    • Transparent Communication
    • Flexible Hiring Modals
    • Fully Signed NDA
    • Cost Effective
    • Easy Exit Policy

    Get in touch with our Sales team

    • sales@ignek.com
    • +91 6351576580
    • IGNEK
    • Ahmedabad, Gujarat, India – 382470
  • SCHEDULE CALL

Creating forms in React with React Hook Form

  • ReactJS
  • September 6, 2024

Share On :

Introduction

React Hook Form is a lightweight and efficient library for managing forms in React applications. It simplifies form handling by reducing re-renders and offering built-in validation, making forms more performant and easier to manage. The library integrates well with existing React components and libraries, providing a streamlined experience without the need for heavy dependencies or complex state management. Its intuitive API makes it easy to adopt, especially for projects where performance and simplicity are key.

Prerequisites
  • Node.js and npm
  • React
  • Typescript
  • React Hook Form
What is React Hook Form & Why?

React Hook Form is a library designed to make form handling in React applications simpler and more efficient. It leverages React’s hooks API to manage form state, validation, and submission in a way that is lightweight and easy to integrate. The library aims to provide a seamless and performant experience for developers working with forms in React.

Advantages of Using React Hook Form
  1. Improved Performance
    • React Hook Form minimizes unnecessary re-renders, which enhances the performance of your forms, especially in complex and large forms.
  2. Simplified Form Management
    • With React Hook Form, managing form state becomes more straightforward. The library abstracts away many of the complexities involved in handling form data, making it easier to manage inputs, errors, and submissions.
  3. Flexibility
    • The library is highly flexible and allows you to use any HTML input elements. It doesn’t force you into a specific pattern or component structure, giving you the freedom to design your form as you see fit.
  1. Enhanced Developer Experience
    • React Hook Form reduces the amount of code needed to build forms, making the developer experience more pleasant. The library’s API is intuitive, and its documentation is thorough, which helps developers get up to speed quickly.
  2. Reduced Bundle Size
    • Compared to other popular form libraries like Formik or Redux Form, React Hook Form has a smaller bundle size, which can lead to faster load times and better overall application performance.
  3. Integration with Existing Tools
    • React Hook Form integrates well with existing form validation libraries like Yup, as well as state management tools, making it a versatile choice for any project.
Features of React Hook Form

Hooks

  1. useForm Hook
    • Description : This is the primary hook provided by React Hook Form. It initializes form handling and returns various methods and objects to manage form state and behavior.
    • Returns : Methods like register, handleSubmit, watch, reset, setValue, and the formState object.
    • Syntax : const { control, handleSubmit, register, formState: { errors } } = useForm<FormValues>()
  2. useFieldArray Hook
    • Description : This hook manages dynamic fields or arrays of fields in forms.
    • Returns : Methods to handle adding, removing, and manipulating field arrays.
    • Syntax : const { fields, append, remove } = useFieldArray({ control, name: ‘dynamicFields’})
  3. useWatch Hook
    • Description : This hook allows you to watch and react to changes in form field values.
    • Returns : The current values of the watched fields.
    • Syntax : const watchedValue = useWatch({ name: ‘username’, control })
Methods and Objects
  1. register Method
    • Description : Registers an input field into the form, enabling it for tracking and validation.
    • Usage : Applied to form fields to capture their values and handle validation.
    • Syntax : <input {…register(‘username’, { required: ‘Username is required’ })} />
  2. handleSubmit Method
    • Description : Wraps your form submission handler, performing validation before invoking the handler.
    • Usage : Used in the onSubmit event of the form element.
    • Syntax : const onSubmit: SubmitHandler<FormValues> = (data) => console.log(data)
      <form onSubmit={handleSubmit(onSubmit)} />
  3. formState Object
    • Description : Contains the state of the form, including information about validation errors, submission status, and whether the form is dirty or valid.
    • Usage : Provides insights into the form’s current status and validation results.
    • Syntax : const { errors, isSubmitting } = formState
  4. Controller Component
    • Description : A component used to wrap controlled components, making them compatible with React Hook Form.
    • Usage : Used to integrate third-party or custom input components with React Hook Form.
    • Syntax : <Controller name=”email” control={control} render={({ field }) => <input {…field}  />} />
  5. control Object
    • Description : An object returned by useForm and used with Controller to manage controlled components.
    • Usage : Passed to the Controller component to link it to the form state.
    • Syntax : const { control } = useForm<FormValues>()
  6. watch Method
    • Description : Monitors changes to specific form fields or the entire form.
    • Usage : Retrieves the current values of watched fields and allows dynamic responses to field changes.
    • Syntax : const username = watch(‘username’)
  7. reset Method
    • Description : Resets the form values to their default state or to specified values.
    • Usage : Clears the form or sets it back to its initial state.
    • Syntax : reset({ username: ”, email: ” })
  8. setValue Method
    • Description : Sets the value of a specific form field programmatically.
    • Usage : Updates field values based on external factors or user interactions.
    • Syntax : setValue(‘username’, ‘NewValue’)
  9. getValues Method
    • Description : Retrieves the current values of all or specific form fields.
    • Usage : Accesses form data without triggering a re-render.
    • Syntax : const values = getValues()
Simplified Form Management : Unlocking the Efficiency of React Hook Form

This application showcases a practical signup form that highlights the ease and efficiency of managing forms using React Hook Form in a React TypeScript environment. The application features a clean, user-friendly signup form with fields for essential user details, including username, email, country, and a tag, along with a checkbox for agreeing to terms.

Built with React and leveraging React Hook Form’s powerful yet minimalist API, the app demonstrates how to handle form state, manage validations, and process user input effectively. By using React Hook Form, the application simplifies form management, making it more intuitive and less cumbersome.

folder-structure
Navigating the Frontend Setup In React

Let’s focus on implementing a signup form using React with TypeScript and React Hook Form. We’ll build an intuitive and user-friendly signup interface, leveraging React Hook Form to manage form state and validation with ease. This guide will demonstrate how to streamline form handling, ensuring a seamless user experience with minimal complexity.

Initializing React Application : To create a React application, you need to start by creating a project folder in your root directory.

				
					//Create react app using the following command
npx create-react-app react-hook-form --template typescript

//Install the required library
npm i react-hook-form


				
			
  • Proceed with the following steps to create the Signup form. In the project react-hook-form folder, locate the App.tsx file which serves as the entry point for the project.

1) Create a separate folder named SignupForm for the components where you will create the necessary components.

2) Inside that folder, create two files: SignupForm.tsx and SignupForm.css.

  1. SignupForm.tsx : This file will contain the React component for the signup form. It will handle the structure, logic, and behavior of the form, including input fields, validation, and event handling.
  2. SignupForm.css : This file will contain the styling rules for the SignupForm component.

3) In this app, raw css is used for styling. Design the user interface according to your preference using raw CSS or any library of your choice.

				
					// App.tsx

// Necessary Imports

function App() { return (<div className = "App"><SignupForm /></ div>); }

export default App;
				
			
  • In the App component, we are rendering the SignupForm component, which is a part of our application’s UI for handling user signup.
				
					//SignupForm.tsx

import { useForm, Controller, SubmitHandler } from 'react-hook-form';

type FormValues = {
  username: string;
  email: string;
  agreeToTerms: boolean;
  country: string;
  tags: string;
};

const SignupForm: React.FC = () => {
  const { control, handleSubmit, setError, formState: { errors, isSubmitting } } = useForm<FormValues>({
    defaultValues: {
      username: '',
      email: '',
      agreeToTerms: false,
      country: '',
      tags: ''
    }
  });

  const validate = (data: FormValues) => {
    const errors: { [key in keyof FormValues]?: string } = {};
  
    if (!data.username || data.username.length < 3) {
      errors.username = 'Username is required and must be at least 3 characters long';
    }
    if (!data.email || !/^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(data.email)) {
      errors.email = 'Invalid email address';
    }
    if (!data.agreeToTerms) {
      errors.agreeToTerms = 'You must agree to the terms and conditions';
    }
    if (!data.country) {
      errors.country = 'Country is required';
    }
    if (!data.tags.trim()) {
      errors.tags = 'Tag is required';
    }
  
    return errors;
  };

  const onSubmit: SubmitHandler<FormValues> = (data) => {
    const validationErrors = validate(data);
    if (Object.keys(validationErrors).length > 0) {
      Object.keys(validationErrors).forEach(key => {
        setError(key as keyof FormValues, {
          type: 'manual',
          message: validationErrors[key as keyof FormValues],
        });
      });
    } else {
      console.log(data);
    }
  };

  return (
    <form onSubmit={handleSubmit(onSubmit)} noValidate className="my-form">
      <div className="form-group">
        <label htmlFor="username" className="label">Username</label>
        <Controller
          name="username"
          control={control}
          render={({ field }) => <input id="username" {...field} className="form-control" />}
        />
        {errors.username && <p className="error-message">{errors.username.message}</p>}
      </div>

      <div className="form-group">
        <label htmlFor="email" className="label">Email</label>
        <Controller
          name="email"
          control={control}
          render={({ field }) => <input type="email" id="email" {...field} className="form-control" />}
        />
        {errors.email && <p className="error-message">{errors.email.message}</p>}
      </div>

      <div className="form-group">
        <label htmlFor="country" className="label">Country</label>
        <Controller
          name="country"
          control={control}
          render={({ field }) => (
            <select id="country" {...field} className="form-control">
              <option value="">Select a country</option>
              <option value="USA">USA</option>
              <option value="Canada">Canada</option>
              <option value="UK">UK</option>
            </select>
          )}
        />
        {errors.country && <p className="error-message">{errors.country.message}</p>}
      </div>

      <div className="form-group">
        <label htmlFor="tags" className="label">Tag</label>
        <Controller
          name="tags"
          control={control}
          render={({ field }) => <input id="tags" {...field} className="form-control" />}
        />
        {errors.tags && <p className="error-message">{errors.tags.message}</p>}
      </div>

      <div className="form-group">
        <Controller
          name="agreeToTerms"
          control={control}
          render={({ field }) => (
            <div className="checkbox-group">
              <input
                type="checkbox"
                id="agreeToTerms"
                checked={field.value}
                onChange={field.onChange}
                className="form-checkbox"
              />
              <label htmlFor="agreeToTerms" className='checkbox-label'>I agree to the terms and conditions</label>
            </div>
          )}
        />
        {errors.agreeToTerms && <p className="error-message">{errors.agreeToTerms.message}</p>}
      </div>

      <button type="submit" disabled={isSubmitting} className="submit-button">Submit</button>
    </form>
  );
};

export default SignupForm;


				
			

This SignupForm component is a React functional component that utilizes React Hook Form for form handling. Here’s a breakdown of its components and how they work:

Key Imports
  • useForm : Manages form state, validation, and submission.
  • Controller : Connects controlled inputs with the form state.
  • SubmitHandler : Defines the type for the submit function.
Form Initialization
  • useForm Hook
    • Sets up the form, manages state, and handles validation/submission.
    • Accepts defaultValues to initialize form fields.
    • Provides methods like control, handleSubmit, and formState.
Validation
  • Custom Validation
    • Validates fields based on custom rules.
    • Returns errors which can be set using setError.
Form Submission
  • handleSubmit Function
    • Ensures validation occurs before submission.
    • Wraps the submit function, triggering validation first.
    • If validation passes, submit the form data for processing.
Form Rendering
  • Form Structure
    • <form> element uses handleSubmit for submission.
    • <Controller> manages each input, connecting it to the form state.
    • Handles different input types like text, dropdown, and checkbox.
    • Displays validation errors next to inputs.
Submit Button
  • Button
    • Triggers form submission.
    • Disabled while the form is being submitted.
Output
output-1
output-2
Conclusion

React Hook Form simplifies form handling in React applications by leveraging hooks to manage form state, validation, and submission with minimal re-renders. Its intuitive API makes it easy to integrate with existing components and validation libraries, reducing boilerplate code and enhancing performance. By providing a streamlined approach to form management, React Hook Form helps developers build efficient, maintainable forms, improving both development speed and user experience.

Explore Our Services

Discover how we can help your business thrive, whether you’re running a small startup, an SME, or a large enterprise. We’re here to understand your unique needs and goals, offering the expertise and resources to support your journey to success.

Stay informed about our ReactJS services and updates by subscribing to our newsletter—just fill in the details below to subscribe.

Loading
Loading...

Related Blogs

March 27, 2024
Authentication and Authorization in React
March 27, 2024
ReactJS Performance Tuning
July 19, 2024
Simplifying State with Context API
Simplifying State with Context API
Loading...

Featured Projects Portfolios

November 27, 2023
Government Job Platform User-Friendly, Secure and Scalable
Government Job Platform : User-Friendly, Secure, and Scalable
October 4, 2023
Telemedicine Appointment & Health Record Portal
Telemedicine Appointment & Health Record Portal

Digital Solutions for Your Business with IGNEK

4.9

5.0

5.0

5.0

LOGO

Making the world a better place through constructing elegant hierarchies

COMPANY

  • About
  • Career
  • Case Study
  • Blogs

SERVICES

  • Enterprise Portal Development
  • Dedicated Development Team
  • Back-end Development
  • Front-end Development
  • Digital Transformation
  • SaaS Development

HIRE US

  • Liferay
  • Spring Boot
  • ReactJS
  • Healthcare
  • MERN Stack
  • AEM

CONTACT

  • info@ignek.com
  • info@ignek.com
SALES
  • sales@ignek.com
  • (+91) 635 157 6580
CAREER
  • hr@ignek.com
  • (+91) 932 849 5160
  • E 910-912, Ganesh Glory 11, Jagatpur Road, SG Highway, Ahmedabad, Gujarat - 382470

© 2018-2025 IGNEK, Inc. All rights reserved

Linkedin Facebook X-twitter Instagram