Blog>
Snippets

Dynamic Form Fields with TanStack Form

Showcase how to dynamically add and remove form fields in a Solid.js application using TanStack Form, including the use of arrays and objects for form state management.
import { createSignal } from 'solid-js';
import { useForm, useFieldArray } from '@tanstack/solid-form';
Imports necessary functions from Solid.js and TanStack Form to manage form states and dynamic field arrays.
const MyDynamicForm = () => {
  const { register, control, handleSubmit } = useForm({
    defaultValues: {
      emails: [{ value: '' }]
    }
  });
  const { fields, append, remove } = useFieldArray({
    control,
    name: 'emails'
  });
Sets up a form with a dynamic array of email fields. 'useForm' initializes the form state with one email field by default. 'useFieldArray' manages the `emails` array.
const onSubmit = data => console.log(data);

  return (
    <form onSubmit={handleSubmit(onSubmit)}>
      {fields.map((field, index) => (
        <div key={field.id}>
          <input
            {...register(`emails.${index}.value`)}
            placeholder='Email'
          />
          <button type='button' onClick={() => remove(index)}>Remove</button>
        </div>
      ))}
      <button type='button' onClick={() => append({ value: '' })}>Add Email</button>
      <button type='submit'>Submit</button>
    </form>
  );
};
Renders the form allowing users to dynamically add or remove email input fields, and submit all input fields' data. 'append' adds a new field, while 'remove' deletes a field.