Field arrays

Felte supports creating fields from arrays by adding an index to its name. There's a few things to consider when working with field arrays:

createForm also returns some helpers to manage field arrays:

Using field arrays would look something like this:

<script>
  import { createForm } from 'felte';

  const { form, data, addField, unsetField } = createForm({
    initialValues: {
      interests: [{ value: '' }],
    },
  });

  $: interests = $data.interests;

  function removeInterest(index) {
    return () => unsetField(`interests.${index}`);
  }

  function addInterest(index) {
    return () => addField(`interests`, { value: '' }, index);
  }
</script>

<form use:form>
  {#each interests as interest, index}
    <div>
      <input name="interests.{index}.value" />
      <button type="button" on:click="{addInterest(index + 1)}">
        Add Interest
      </button>
      <button type="button" on:click="{removeInterest(index)}">
        Remove Interest
      </button>
    </div>
  {/each}
</form>