react hook form

React Hook Form - A Complete Guide

If you are looking for a lightweight library to handle forms in React, React Hook Form is the way to go. It is a simple and intuitive library that makes form handling a breeze, without any additional complexities.

Installation

First, install the library using npm:

npm install react-hook-form

Then, import the useForm hook in your component:

import { useForm } from 'react-hook-form';

Usage

Now that you have installed the library and imported the hook, you can use it in your component. Here's an example:

import React from 'react';
import { useForm } from 'react-hook-form';

function MyForm() {
  const { register, handleSubmit, errors } = useForm();

  function onSubmit(data) {
    console.log(data);
  }

  return (
    <form onSubmit={handleSubmit(onSubmit)}>
      <input name="firstName" ref={register({ required: true })} />
      {errors.firstName && <p>This field is required</p>}
      
      <input name="lastName" ref={register({ required: true })} />
      {errors.lastName && <p>This field is required</p>}
      
      <input type="submit" />
    </form>
  );
}

export default MyForm;

In the above example, we are defining a form with two input fields (firstName and lastName), and a submit button. We are also defining an onSubmit function that will be called when the form is submitted.

We are using the useForm hook to register the form inputs, handle form submission, and handle form errors.

The register function is used to register the form inputs. We are passing an object with a required property to validate the inputs. If the input is not filled in, a message will be displayed below the input field.

The handleSubmit function is used to handle form submission. It takes the onSubmit function as an argument and calls it when the form is submitted.

The errors object is used to handle form errors. If any error occurs, it will be added to this object, and we can display the error message accordingly.

Validation

React Hook Form provides an easy way to validate form inputs. You can add validation rules to each input using the register function. Here are some examples:

  • required: true - The input is required.
  • minLength: 2 - The input must have at least 2 characters.
  • maxLength: 20 - The input can have a maximum of 20 characters.
  • pattern: /^[A-Za-z]+$/i - The input can only contain alphabets.

You can also define custom validation rules using the validate function. Here's an example:

const { register, handleSubmit, errors } = useForm({
  validate: values => {
    const errors = {};
    if (!/^[A-Za-z]+$/i.test(values.firstName)) {
      errors.firstName = 'Invalid first name';
    }
    return errors;
  }
});

In this example, we are defining a custom validation rule for the firstName input. We are using a regular expression to validate the input, and if the input is invalid, we are adding an error message to the errors object.

Conclusion

React Hook Form is a lightweight library that simplifies form handling in React. It provides an easy way to register form inputs, handle form submission, and validate form inputs. It is a great choice for anyone looking for a simple and intuitive form handling library.

Subscribe to The Poor Coder | Algorithm Solutions

Don’t miss out on the latest issues. Sign up now to get access to the library of members-only issues.
[email protected]
Subscribe