logo
eng-flag

React Hook Form Cheatsheet

Table of Contents

  1. Installation
  2. Basic Usage
  3. Form Validation
  4. Field Arrays
  5. Watch Fields
  6. Handling Submission
  7. Error Handling
  8. Form State
  9. Custom Inputs
  10. Conditional Fields
  11. Integration with UI Libraries

Installation

Install React Hook Form:

npm install react-hook-form

Basic Usage

Basic form setup with React Hook Form:

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

function MyForm() {
  const { register, handleSubmit } = useForm();
  
  const onSubmit = (data) => console.log(data);

  return (
    <form onSubmit={handleSubmit(onSubmit)}>
      <input {...register("firstName")} />
      <input {...register("lastName")} />
      <input type="submit" />
    </form>
  );
}

Form Validation

Adding validation to form fields:

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

function ValidationForm() {
  const { register, handleSubmit, formState: { errors } } = useForm();
  
  return (
    <form onSubmit={handleSubmit(onSubmit)}>
      <input 
        {...register("email", { 
          required: "Email is required",
          pattern: {
            value: /^[A-Z0-9._%+-]+@[A-Z0-9.-]+.[A-Z]{2,}$/i,
            message: "Invalid email address"
          }
        })}
      />
      {errors.email && <span>{errors.email.message}</span>}
      
      <input 
        {...register("password", { 
          required: "Password is required",
          minLength: {
            value: 8,
            message: "Password must be at least 8 characters"
          }
        })}
      />
      {errors.password && <span>{errors.password.message}</span>}
      
      <input type="submit" />
    </form>
  );
}

Field Arrays

Working with dynamic form fields:

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

function FieldArrayForm() {
  const { register, control, handleSubmit } = useForm();
  const { fields, append, remove } = useFieldArray({
    control,
    name: "items"
  });

  return (
    <form onSubmit={handleSubmit(onSubmit)}>
      {fields.map((field, index) => (
        <div key={field.id}>
          <input {...register(`items.${index}.name`)} />
          <button type="button" onClick={() => remove(index)}>Delete</button>
        </div>
      ))}
      <button type="button" onClick={() => append({ name: "" })}>Add Item</button>
      <input type="submit" />
    </form>
  );
}

Watch Fields

Watching form field values:

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

function WatchForm() {
  const { register, watch } = useForm();
  const watchShowAge = watch("showAge", false);
  
  return (
    <form>
      <input type="checkbox" {...register("showAge")} />
      {watchShowAge && (
        <input type="number" {...register("age")} />
      )}
    </form>
  );
}

Handling Submission

Handling form submission with async operations:

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

function SubmissionForm() {
  const { register, handleSubmit, formState: { isSubmitting } } = useForm();
  
  const onSubmit = async (data) => {
    await new Promise(resolve => setTimeout(resolve, 1000));
    console.log(data);
  };

  return (
    <form onSubmit={handleSubmit(onSubmit)}>
      <input {...register("username")} />
      <button type="submit" disabled={isSubmitting}>
        {isSubmitting ? 'Submitting...' : 'Submit'}
      </button>
    </form>
  );
}

Error Handling

Detailed error handling:

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

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

  return (
    <form onSubmit={handleSubmit(onSubmit)}>
      <input {...register("email", { required: "Email is required" })} />
      {isSubmitted && errors.email && <span>{errors.email.message}</span>}
      
      <input type="submit" />
    </form>
  );
}

Form State

Accessing and using form state:

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

function StateForm() {
  const { 
    register, 
    handleSubmit, 
    formState: { 
      isDirty, 
      isSubmitting, 
      isSubmitted, 
      submitCount 
    } 
  } = useForm();

  return (
    <form onSubmit={handleSubmit(onSubmit)}>
      <input {...register("example")} />
      <p>Form is dirty: {isDirty.toString()}</p>
      <p>Form is submitting: {isSubmitting.toString()}</p>
      <p>Form is submitted: {isSubmitted.toString()}</p>
      <p>Submit count: {submitCount}</p>
      <input type="submit" />
    </form>
  );
}

Custom Inputs

Creating custom form inputs:

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

function CustomInputForm() {
  const { control } = useForm();

  return (
    <form>
      <Controller
        name="select"
        control={control}
        render={({ field }) => (
          <Select 
            {...field} 
            options={[
              { value: 'chocolate', label: 'Chocolate' },
              { value: 'strawberry', label: 'Strawberry' },
              { value: 'vanilla', label: 'Vanilla' }
            ]} 
          />
        )}
      />
    </form>
  );
}

Conditional Fields

Implementing conditional form fields:

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

function ConditionalForm() {
  const { register, watch } = useForm();
  const watchShowEmail = watch("showEmail", false);

  return (
    <form>
      <input type="checkbox" {...register("showEmail")} />
      {watchShowEmail && (
        <input {...register("email", { required: true })} />
      )}
    </form>
  );
}

Integration with UI Libraries

Example with Material-UI:

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

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

  return (
    <form onSubmit={handleSubmit(onSubmit)}>
      <Controller
        name="textField"
        control={control}
        defaultValue=""
        rules={{ required: 'This field is required' }}
        render={({ field, fieldState: { error } }) => (
          <TextField
            {...field}
            label="Example"
            error={!!error}
            helperText={error ? error.message : null}
          />
        )}
      />
      <Button type="submit" variant="contained" color="primary">
        Submit
      </Button>
    </form>
  );
}

2024 © All rights reserved - buraxta.com