乐闻世界logo
搜索文章和话题

How to dynamic add rows of fields in React Hook Forms

1个答案

1

Answer:

When using React Hook Form, dynamically adding form rows typically involves managing array-type form fields. In this case, we typically use the useFieldArray Hook, which is specifically designed for handling array fields, such as dynamically adding, deleting, and updating items within the array.

Step 1: Import Necessary Hooks

First, we need to import useForm and useFieldArray from react-hook-form.

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

Step 2: Set Up the Form

Next, we use useForm to initialize the form.

javascript
const { control, handleSubmit, register } = useForm({ defaultValues: { rows: [] } });

Here, defaultValues is configured with an empty array for rows, which serves as the container for dynamically adding data.

Step 3: Use useFieldArray

We employ useFieldArray to manage the rows array.

javascript
const { fields, append, remove } = useFieldArray({ control, name: "rows" // Ensure this matches your form's default values });

Step 4: Implement Add Operations

To dynamically add rows, we can create a function that, when invoked, uses the append method to add new data objects to the rows array.

javascript
const addRow = () => { append({ name: "", age: "" }); };

Step 5: Render the Form and Rows

In the return section of the React component, we iterate over fields to render each row and include a delete button for removal.

javascript
<form onSubmit={handleSubmit(onSubmit)}> {fields.map((field, index) => ( <div key={field.id}> <input {...register(`rows.${index}.name`)} placeholder="Name" /> <input {...register(`rows.${index}.age`)} placeholder="Age" /> <button type="button" onClick={() => remove(index)}>Delete</button> </div> ))} <button type="button" onClick={addRow}>Add Row</button> <input type="submit" /> </form>

Example Illustration

Suppose we are building a form for entering multiple member details. Users can add additional input fields for members by clicking the 'Add Row' button, and each row includes a delete button to remove unnecessary entries. The above code supports this scenario effectively.

Conclusion

By leveraging useFieldArray, React Hook Form offers a streamlined approach to handling array fields in forms, enabling both simplicity and efficiency in dynamically adding and deleting form rows.

2024年6月29日 12:07 回复

你的答案