Back to articles

Level Up Your React Forms: Mastering React Hook Form v8

AuthorMajd Muhtaseb08/21/20257 minutes
Level Up Your React Forms: Mastering React Hook Form v8

Introduction

React Hook Form is a powerful library for building performant and user-friendly forms in React. Version 8 brings further improvements in terms of performance, flexibility, and developer experience. This article dives into key features and demonstrates practical implementation.

Installation

First, install the library:

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

Basic Usage

Here's a basic example of a simple form:

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

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

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

  return (
    <form onSubmit={handleSubmit(onSubmit)}>
      <label htmlFor="firstName">First Name:</label>
      <input type="text" id="firstName" {...register("firstName", { required: "First name is required" })} />
      {errors.firstName && <p>{errors.firstName.message}</p>}

      <label htmlFor="lastName">Last Name:</label>
      <input type="text" id="lastName" {...register("lastName")} />

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

export default MyForm;

Explanation:

  • useForm hook: This hook provides the core functionality for managing form state.
  • register: This function is used to register input fields and attach validation rules. The spread operator (...) passes the necessary props to the input element.
  • handleSubmit: This function wraps your form submission logic.
  • formState.errors: This object contains any validation errors.

Advanced Validation

React Hook Form provides robust validation capabilities. You can define validation rules directly within the register function:

<input
  type="email"
  id="email"
  {...register("email", {
    required: "Email is required",
    pattern: {
      value: /^[^\s@]+@[^\s@]+\.[^\s@]+$/,
      message: "Invalid email format",
    },
  })}
/>
{errors.email && <p>{errors.email.message}</p>}

Explanation:

  • required: Makes the field mandatory.
  • pattern: Uses a regular expression to validate the email format.
  • Error messages are displayed conditionally based on the presence of errors.

Controlled Components

React Hook Form can seamlessly integrate with controlled components. You can use Controller component to manage state and pass the values to your UI.

import { useForm, Controller } from 'react-hook-form';
import Select from 'react-select'; // Assuming you have react-select installed

function MyFormWithSelect() {
    const { control, handleSubmit } = useForm();

    const options = [
        { value: 'chocolate', label: 'Chocolate' },
        { value: 'strawberry', label: 'Strawberry' },
        { value: 'vanilla', label: 'Vanilla' },
    ];

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

    return (
        <form onSubmit={handleSubmit(onSubmit)}>
            <Controller
                name="flavor"
                control={control}
                defaultValue={null}
                render={({ field }) => (
                    <Select
                        {...field}
                        options={options}
                        isClearable
                    />
                )}
            />
            <button type="submit">Submit</button>
        </form>
    );
}

export default MyFormWithSelect;

Conclusion

React Hook Form simplifies form management in React applications. Its hook-based approach, validation capabilities, and support for controlled components make it a valuable tool for any React developer. Version 8 further enhances its usability and performance. Remember to refer to the official documentation for more detailed information and advanced features.