author avatar

amber.srivastava

Thu Nov 14 2024

------------------------- useFieldArray hook in react-hook-form -------------------------
The useFieldArray hook is part of react-hook-form and is used for handling dynamic fields in forms, such as arrays of inputs that can be added or removed dynamically.
For example, if you have a list of items (like questions, tasks, or other fields) that can be added, removed, or reordered during form submission, useFieldArray is the ideal solution to manage that dynamic behaviour without manually managing the state of each individual field.

How useFieldArray works:
fields: An array of objects, where each object represents a field in the array.
append: A function to add new fields to the array.
remove: A function to remove fields from the array.
update: A function to update an individual field in the array.
Example:-


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

function DynamicForm() {
  const { register, control, handleSubmit, formState: { errors } } = useForm({
    defaultValues: {
      questions: [{ question: "" }],
    },
  });

  // UseFieldArray to handle the questions array dynamically
  const { fields, append, remove } = useFieldArray({
    control,
    name: "questions",  // Name of the array in the form's state
  });

  const onSubmit = (data: any) => {
    console.log(data); // Submitting form data with dynamic fields
  };

  return (
    <form onSubmit={handleSubmit(onSubmit)}>
      {fields.map((item, index) => (
        <div key={item.id}>
          <input
            {...register(`questions.${index}.question`)}  // Register each question dynamically
            defaultValue={item.question}  // Set default value for each item in the array
          />
          {errors.questions?.[index]?.question && (
            <span>{errors.questions[index]?.question.message}</span>
          )}
          <button type="button" onClick={() => remove(index)}>Remove</button>
        </div>
      ))}
      
      <button type="button" onClick={() => append({ question: "" })}>
        Add Question
      </button>

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


Key Points:
1. name: The name prop in useFieldArray points to the field array in your form state (in this case, questions).
2. fields: This array holds the current data of the dynamic fields. Each item corresponds to a field in the form array.
3. append: This method is used to add a new item to the array. You can pass the new data for the item when appending.
4. remove: This method is used to remove an item by its index.
When to use useFieldArray:
Dynamic Forms: When you have a form where the number of fields can change over time, such as adding/removing questions, tasks, team members, etc.
Nested Fields: When you have an array of objects (e.g., an array of questions, where each question has a title and description).
Advantages:
• It reduces the need for manual state management when adding/removing fields.
• It integrates seamlessly with react-hook-form to handle validations and form submission.
• It improves performance by avoiding unnecessary re-renders when fields are added or removed.
#CCT1JMA0Z #useForm #react-hook-form