Clue Mediator

Dynamic form with React Hook Form using useFieldArray

πŸ“…January 7, 2023
πŸ—ReactJS

In this article, we will show you how to work with dynamic form with React Hook Form using useFieldArray in React. You may need to consider an array in form in real project so here you will learn how to manage array form using the react-hook-form.

Demo Application

Output - Dynamic form with React Hook Form using useFieldArray - Clue Mediator

Output - Dynamic form with React Hook Form using useFieldArray - Clue Mediator

Dynamic form with React Hook Form using useFieldArray

  1. Project structure
  2. Package dependencies
  3. Create a dynamic form
  4. Output

1. Project structure

Refer to the following project structure for the dynamic form.

  • dynamic-form-react-hook-form

    • node_modules

    • public

      • index.html
    • src

      • App.js
      • index.css
      • index.js
    • package-lock.json

    • package.json

    • README.md

2. Package dependencies

In this example, we have to install the react-hook-form npm package. Run the following command to install the `react-hook-form`.

npm i react-hook-form

You will find the version of following packages in React application.

react

^18.2.0

react-hook-form

^7.41.3

3. Create a dynamic form

Steps to implement a dynamic form.

  • Use `useFieldArray` from the react-hook-form.
  • Define the name called `list` of an array and export `fields`, `append`, and `remove` from the `useFieldArray`.
  • Here, we have to use the `append()` and `remove()` method to add or remove items from the list.
  • At last we have to register the field using index like `list.${index}.firstName`.

Refer to the following code for the dynamic array list.

App.js

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

const App = () => {
  const [data, setData] = useState();
  const { control, register, handleSubmit } = useForm({
    defaultValues: {
      list: [{ firstName: '', lastName: '' }]
    }
  });
  const { fields, append, remove } = useFieldArray({
    control,
    name: "list"
  });

  const onSave = data => {
    setData({ ...data });
  }

  return <form onsubmit={handleSubmit(onSave)}>
    <h4>Dynamic form with react-hook-form using useFieldArray - <a href="https://www.cluemediator.com/" target="_blank" rel="noopener noreferrer">Clue Mediator</a></h4>
    {fields.map((field, index) => (
      <div class="box" key={field.id}>
        <div>
          <input placeholder="Enter First Name" {...register(`list.${index}.firstname`)}="">
        </div>
        <div>
          <input class="ml10" placeholder="Enter Last Name" {...register(`list.${index}.lastname`)}="">
        </div>
        <div class="btn-box">
          {fields.length !== 1 && <button class="mr10" onclick="{()" ==""> remove(index)}>Remove</button>}
          {fields.length - 1 === index && <button onclick="{()" ==""> append({ firstName: '', lastName: '' })}>Add</button>}
        </div>
      </div>
    ))}
    <button>Submit</button>
    {data && <pre>{JSON.stringify(data, null, 2)}</pre>}
  </form>
}

export default App;

4. Output

Run the application and check the output in the browser.

I hope you find this article helpful.
Thank you for reading. Happy Coding..!! πŸ™‚

Demo & Source Code

GitHub Repository StackBlitz Project