useFieldArray in React Hook Form

Dec 6, 2024 · 2 min read · 237 Words · -Views -Comments · Programming
React 🇨🇳 阅读中文版
Read with AI

Choose an AI assistant

ChatGPT Open in a new tab with the article link and prompt
Claude Copy the prompt, then open Claude

Open Claude
Trouble reading the article?

If the prompt is missing, copy the full prompt below into your AI assistant. If the AI cannot read the article, paste the visible passage you want to discuss and add your question.

In web page interactions, forms are common elements. For form validation/management, react-hook-form is a commonly used and excellent helper library. For example, useFieldArray is used for managing array values, and formContext is used for complex nested component forms. Understanding these usage patterns helps you use it more effectively.

Use Case

When handling forms, you sometimes need to process array form items, such as when users can dynamically add N rows of form items. useFieldArray is designed for this type of array handling.

Example

function FormTest() {
  const {control, register, getValues} = useForm();
  const {fields, append, prepend, remove, swap, move, insert} = useFieldArray({
    control, // control props comes from useForm (optional: if you are using FormProvider)
    name: "test", // unique name for your Field Array
  });

  console.log(fields, 'fields');
  return (
    <form>
      {fields.map((field, index) => (
        <div><input
          key={field.id} // important to include key with field's id
          {...register(`test.${index}.value`)}
        /></div>
      ))}

      <Button onClick={() => {
        append({
          value: 1,
        })
      }}>
        Add
      </Button>
      {
        JSON.stringify(getValues())
      }
    </form>
  );
}

As shown above, when clicking the Button to add, fields can automatically insert a new value, and each value can also be monitored and maintained through register/controller.

Important Details

The append value must be an object - for example, append(1) won’t work. This means fields must maintain objects, so test.${index}.value cannot be set as test.${index}.

https://static.1991421.cn/2024/2024-12-06-182851.jpeg

Final Thoughts

For form handling requirements, I recommend trying this library as a solution.

Authors
Developer, digital product enthusiast, tinkerer, sharer, open source lover