Written by: Geoffrey Callaghan

React Hook Form Tutorial

React Hook Form Tutorial

React Hook Form is a library designed to make form handling in React easier by using hooks to manage form state and validation. It’s lightweight and efficient, providing a straightforward way to build forms in React. Here’s a step-by-step tutorial to help you get started with React Hook Form.

Step 1: Setup Your React Application

First, ensure you have a React application set up. If you don’t have one already, you can create a new one using Create React App:

npx create-react-app my-rhf-app
cd my-rhf-app

Step 2: Install React Hook Form

Install React Hook Form using npm or yarn:

npm install react-hook-form
# or
yarn add react-hook-form

Step 3: Basic Usage of React Hook Form

Let’s create a simple form to collect user information (name and email).

  1. Create a new component (e.g., MyForm.js):
import React from 'react';
import { useForm } from 'react-hook-form';

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

  const onSubmit = data => {
    alert(JSON.stringify(data, null, 2));
  };

  return (
    <form onSubmit={handleSubmit(onSubmit)}>
      <div>
        <label htmlFor="name">Name</label>
        <input id="name" {...register('name', { required: true })} />
        {errors.name && <p>Name is required</p>}
      </div>
      <div>
        <label htmlFor="email">Email</label>
        <input id="email" {...register('email', { required: true })} />
        {errors.email && <p>Email is required</p>}
      </div>
      <button type="submit">Submit</button>
    </form>
  );
};

export default MyForm;
  1. Include this component in your main application file (e.g., App.js):
import React from 'react';
import MyForm from './MyForm';

const App = () => (
  <div>
    <h1>My React Hook Form</h1>
    <MyForm />
  </div>
);

export default App;

Step 4: Adding Validation

React Hook Form allows you to add validation rules easily.

  1. Update your form component to include validation rules:
import React from 'react';
import { useForm } from 'react-hook-form';

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

  const onSubmit = data => {
    alert(JSON.stringify(data, null, 2));
  };

  return (
    <form onSubmit={handleSubmit(onSubmit)}>
      <div>
        <label htmlFor="name">Name</label>
        <input 
          id="name" 
          {...register('name', { 
            required: 'Name is required', 
            maxLength: { value: 15, message: 'Name must be 15 characters or less' } 
          })} 
        />
        {errors.name && <p>{errors.name.message}</p>}
      </div>
      <div>
        <label htmlFor="email">Email</label>
        <input 
          id="email" 
          {...register('email', { 
            required: 'Email is required', 
            pattern: { value: /^[a-zA-Z0-9_.+-]+@[a-zA-Z0-9-]+\.[a-zA-Z0-9-.]+$/, message: 'Invalid email address' } 
          })} 
        />
        {errors.email && <p>{errors.email.message}</p>}
      </div>
      <button type="submit">Submit</button>
    </form>
  );
};

export default MyForm;

Step 5: Enhancing the Form

React Hook Form provides more features to handle complex forms. Here’s a brief overview of some additional functionalities:

  1. Custom Validation: You can write custom validation logic.
import React from 'react';
import { useForm } from 'react-hook-form';

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

  const onSubmit = data => {
    alert(JSON.stringify(data, null, 2));
  };

  return (
    <form onSubmit={handleSubmit(onSubmit)}>
      <div>
        <label htmlFor="name">Name</label>
        <input 
          id="name" 
          {...register('name', { 
            required: 'Name is required', 
            validate: value => value !== 'admin' || 'Cannot use "admin" as name'
          })} 
        />
        {errors.name && <p>{errors.name.message}</p>}
      </div>
      <div>
        <label htmlFor="email">Email</label>
        <input 
          id="email" 
          {...register('email', { 
            required: 'Email is required', 
            pattern: { value: /^[a-zA-Z0-9_.+-]+@[a-zA-Z0-9-]+\.[a-zA-Z0-9-.]+$/, message: 'Invalid email address' } 
          })} 
        />
        {errors.email && <p>{errors.email.message}</p>}
      </div>
      <button type="submit">Submit</button>
    </form>
  );
};

export default MyForm;
  1. Handling Arrays: Use useFieldArray for managing arrays of fields.

  2. Integrating with UI Libraries: React Hook Form can integrate with various UI libraries like Material-UI, Ant Design, etc.

Conclusion

React Hook Form is a powerful library for handling forms in React applications. It provides an easy way to manage form state, validation, and submission. This tutorial covers the basics, but React Hook Form has many more features that you can explore in its official documentation.