Written by: Geoffrey Callaghan

Making forms easier with react-hook-form

Making Forms Easier With React-Hook-Form

Using react-hook-form can greatly simplify form handling in React applications by providing a clean, declarative way to manage form state, validation, and submission. Here’s a guide on how to use react-hook-form to make forms easier in React.

1. Installation

First, you need to install react-hook-form:

npm install react-hook-form

2. Basic Usage

To start using react-hook-form, you need to import and initialize it in your form component.

Step-by-Step Example

  1. Import Required Hooks and Components:
import React from 'react';
import { useForm } from 'react-hook-form';
  1. Initialize useForm:
const { register, handleSubmit, formState: { errors } } = useForm();
  1. Create the Form Component:
function MyForm() {
  const { register, handleSubmit, formState: { errors } } = useForm();

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

  return (
    <form onSubmit={handleSubmit(onSubmit)}>
      <div>
        <label htmlFor="name">Name</label>
        <input id="name" {...register('name', { required: true })} />
        {errors.name && <span>This field is required</span>}
      </div>

      <div>
        <label htmlFor="email">Email</label>
        <input id="email" {...register('email', { required: true, pattern: /^[^@\s]+@[^@\s]+\.[^@\s]+$/ })} />
        {errors.email && <span>Invalid email address</span>}
      </div>

      <button type="submit">Submit</button>
    </form>
  );
}

export default MyForm;

3. Validation

react-hook-form provides robust validation features that can be added declaratively. You can use validation rules directly in the register function.

Common Validation Rules

  • required: Field must be filled out.
  • pattern: Field must match the specified regular expression.
  • minLength and maxLength: Field value must have a certain length.
  • min and max: Field value must be within a certain range.

Example with Validation

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

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

  return (
    <form onSubmit={handleSubmit(onSubmit)}>
      <div>
        <label htmlFor="username">Username</label>
        <input id="username" {...register('username', { required: 'Username is required' })} />
        {errors.username && <span>{errors.username.message}</span>}
      </div>

      <div>
        <label htmlFor="password">Password</label>
        <input id="password" type="password" {...register('password', { required: 'Password is required', minLength: { value: 6, message: 'Password must be at least 6 characters' } })} />
        {errors.password && <span>{errors.password.message}</span>}
      </div>

      <div>
        <label htmlFor="email">Email</label>
        <input id="email" {...register('email', { required: 'Email is required', pattern: { value: /^[^@\s]+@[^@\s]+\.[^@\s]+$/, message: 'Invalid email address' } })} />
        {errors.email && <span>{errors.email.message}</span>}
      </div>

      <button type="submit">Submit</button>
    </form>
  );
}

export default MyForm;

4. Handling Form Submission

The handleSubmit function provided by useForm manages the form submission process. It ensures that validation is performed before calling your custom submit handler.

Example

const onSubmit = data => {
  console.log('Form Data:', data);
};

<form onSubmit={handleSubmit(onSubmit)}>
  <!-- form fields -->
</form>

5. Resetting the Form

To reset the form, you can use the reset function provided by useForm.

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

const onSubmit = data => {
  console.log(data);
  reset(); // Reset form after submission
};

6. Integrating with Third-Party UI Libraries

You can integrate react-hook-form with UI libraries like Material-UI, Ant Design, etc., by using their components in place of standard HTML inputs and wrapping them with register.

Example with Material-UI

import React from 'react';
import { useForm } from 'react-hook-form';
import TextField from '@material-ui/core/TextField';
import Button from '@material-ui/core/Button';

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

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

  return (
    <form onSubmit={handleSubmit(onSubmit)}>
      <div>
        <TextField
          label="Name"
          {...register('name', { required: 'Name is required' })}
          error={!!errors.name}
          helperText={errors.name?.message}
        />
      </div>

      <div>
        <TextField
          label="Email"
          {...register('email', { required: 'Email is required', pattern: { value: /^[^@\s]+@[^@\s]+\.[^@\s]+$/, message: 'Invalid email address' } })}
          error={!!errors.email}
          helperText={errors.email?.message}
        />
      </div>

      <Button type="submit" variant="contained" color="primary">Submit</Button>
    </form>
  );
}

export default MyForm;

Conclusion

react-hook-form makes handling forms in React simple and efficient. It provides powerful features for managing form state and validation while keeping the code concise and easy to read. Whether you are building simple forms or complex multi-step forms, react-hook-form can help you manage the process effectively.