# Arrays

> Render a list of rows, and add, remove and move them, with the arrays() plugin.

Source: https://forms.lunarhue.dev/solid/plugins/arrays

A form that lists things, such as tasks, order lines or phone numbers, needs
rows the user can add, remove and reorder, each keeping its own input state
as it moves. `arrays()` brings that: `Items` renders one child per row, and
the array's handle has the commands that change the list.

```tsx title="checklist.tsx"
import { Items, createForm, createForms } from "@lunarhue/forms-solid";
import { arrays } from "@lunarhue/forms-solid/plugins";
import { Show } from "solid-js";
import { TextField } from "./TextField";

// arrays() brings Items and the array commands: push, insert, remove, move.
const forms = createForms({ plugins: [arrays()], fields: { TextField } });

// With no schema, `defaultValues` types the form.
const checklist = forms.define({
  defaultValues: {
    tasks: [{ title: "Write the docs" }, { title: "Ship it" }],
  },
  onSubmit: (value) => value.tasks,
});

export default function ChecklistForm() {
  const form = createForm(checklist, { id: "checklist" });
  // A handle to the array. Its commands change the list.
  const tasks = form.root.at("tasks");
  return (
    <form.Form>
      {(formProps) => (
        <form {...formProps}>
          {/* Each row renders once per key. A move or a remove keeps
              the row's DOM, and `index` is a signal that follows it. */}
          <Items handle={tasks}>
            {(task, index) => (
              <div>
                <form.TextField handle={task.at("title")} label={`Task ${index() + 1}`} />
                <div>
                  <button type="button" disabled={index() === 0} onClick={() => tasks.move(index(), index() - 1)}>
                    Up
                  </button>
                  <button type="button" onClick={() => tasks.remove(index())}>
                    Remove
                  </button>
                </div>
              </div>
            )}
          </Items>
          <div>
            <button type="button" onClick={() => tasks.push({ title: "" })}>
              Add task
            </button>
            <button type="submit">Save</button>
          </div>
          <p role="status">
            <Show when={form.state.submission.status === "succeeded" && form.state.submission}>
              {(submission) => submission().result.map((task) => task.title).join(", ")}
            </Show>
          </p>
        </form>
      )}
    </form.Form>
  );
}
```

```tsx title="TextField.tsx"
import { type FieldApi, inputProps } from "@lunarhue/forms-solid";

interface TextFieldProps {
  readonly field: FieldApi<string>;
  readonly label: string;
}

export function TextField(props: TextFieldProps) {
  return (
    <label>
      {props.label}
      <input {...inputProps(props.field)} />
    </label>
  );
}
```

## Installing arrays()

Install `arrays()` on every form that renders or changes a list:

```tsx
import { arrays } from "@lunarhue/forms-solid/plugins";

const forms = createForms({ plugins: [arrays()] });
```

You can also put it in one definition's `plugins`. On a form without it,
passing an array handle to `Items`, `useItems` or `createItems`, or calling
`push`, `insert`, `remove` or `move`, is a type error that says "Add arrays()
to this form's plugins". A form with no lists leaves it out and ships less
code.

## Rendering rows

`Items` takes the array's handle and a function that gets each row's handle
and its index:

```tsx
import { Items } from "@lunarhue/forms-solid";

<Items handle={form.root.at("tasks")}>
  {(task, index) => <form.TextField handle={task.at("title")} label={`Task ${index() + 1}`} />}
</Items>
```

`index` is an accessor. A row renders once, and `index()` follows it when
it moves. `fallback` is shown while the list is empty.

Rows have no names, since a name like `tasks.0.title` would point at another
row after a move. Reach into a row through its handle: `task.at("title")`.

`Items` updates when a row is added, removed or moved. Typing in a row
doesn't re-render the list.

## Changing the list

The array's handle has the commands. Get it with `form.root.at("tasks")`:

| Command | What it does |
| --- | --- |
| `push(item?)` | Adds a row at the end. |
| `insert(index, item?)` | Adds a row before `index`. |
| `remove(index)` | Removes the row at `index`. |
| `move(from, to)` | Moves a row. |
| `setValue(items)` | Replaces the whole list. |

With no `item`, `push` and `insert` add an empty row built from the schema,
or `undefined` when the form has none.

## Keys

Each row gets a key when it is added. The key stays with the row through
moves and removes, and so does its handle: `task` is the same object for
that row for the life of the form, and `task.key` is its key. `Items`
uses the key for the list key, so an input keeps its focus and its text
while its row moves. The current keys, in order, are the array snapshot's
`keys`, and `tasks.item(key)` returns a row's handle.

For a list you lay out yourself, `createItems(handle)` returns an accessor
of the row handles in order, which changes only when the keys do. Pass it to
`<For each={items()}>`.

## Without arrays()

A form without `arrays()` can still hold an array and replace it whole with
`setValue`, as a value the user doesn't edit row by row. Rendering its rows
isn't supported, and the types reject `Items`, `useItems` and
`createItems` for it.

Code without types that calls a command throws
[`arrays:missing`](https://forms.lunarhue.dev/errors.md#core:arrays:missing) in development, and the
commands do nothing in production.

Inside the store, each row's key is then its position: `k0`, `k1`, and so
on. The key and the row's state, such as touched, belong to the position,
not to the item in it. Write `["a", "b"]` over `["a", "b", "c"]` and the
third row goes away. Write `["a", "b", "d"]` after that and the third row
comes back with `"d"` in it, under its old key, still touched if it was.
With `arrays()` the old third row stays gone, and `"d"` gets a new key and
fresh state.

## Errors on the list

A rule about the list as a whole, such as "add at least one task", puts its
error on the array field, not on a row. Render it next to the rows:

```tsx
const list = createField(tasks); // list.shownErrors
```

## Reusable lists

A list component shared by many forms is generic in its item. See
[Reusable lists](https://forms.lunarhue.dev/solid/plugin-composition/lists.md).
