Dynamic Form Field Generation
Shows how to dynamically add and remove input fields in a form managed by the TanStack Form library based on user actions.
import { useForm, useFieldArray } from '@tanstack/react-form';
import React from 'react';
Imports necessary hooks from TanStack Form and React.
function DynamicForm() {
const form = useForm({
defaultValues: { fields: [{ value: '' }] }
});
const fields = useFieldArray({
form,
name: 'fields'
});
Defines a DynamicForm component using useForm to initialize form state with default values for fields and useFieldArray for dynamic field array management.
const addField = () => fields.append({ value: '' });
Defines a function to add a new field to the form.
const removeField = index => fields.remove(index);
Defines a function to remove a field from the form by index.
return (
<form onSubmit={form.handleSubmit(data => console.log(data))}>
{fields.fields.map((field, index) => (
<div key={field.id}>
<input {...form.register(`fields.${index}.value`)} />
<button type='button' onClick={() => removeField(index)}>Remove</button>
</div>
))}
<button type='button' onClick={addField}>Add Field</button>
<button type='submit'>Submit</button>
</form>
);
}
Returns JSX for the form, mapping over fields to render each with an input and remove button, and providing buttons to add a new field or submit the form.
export default DynamicForm;
Exports the DynamicForm component.