Dynamic form with React Hook Form using useFieldArray
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
Dynamic form with React Hook Form using useFieldArray
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
.
1 | npm i react-hook-form |
You will find the version of following packages in React application.
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 exportfields
,append
, andremove
from theuseFieldArray
. - Here, we have to use the
append()
andremove()
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.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 | 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 className="box" key={field.id}> <div> <input placeholder="Enter First Name" {...register(`list.${index}.firstName`)} /> </div> <div> <input className="ml10" placeholder="Enter Last Name" {...register(`list.${index}.lastName`)} /> </div> <div className="btn-box"> {fields.length !== 1 && <button className="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..!! 🙂