Command palette

@yasinsensoy/web

Web · Components

FieldArray

Repeating form rows with a ready-made look: title, rows, remove / duplicate buttons, drag to reorder (sortable), add button, empty state and the array's error.

7 exports

Live example

Preview

Items

Add, delete, duplicate rows; drag by the handle or focus the handle and use Alt + ↑/↓.

Code

import { Form, FieldArray, TextField, NumberField, SubmitButton } from "@yasinsensoy/web";

const Invoice = z.object({
  items: z.array(z.object({ name: z.string().min(1), quantity: z.number().min(1) }))
    .min(1, "En az bir kalem ekle"),
});

<Form schema={Invoice} defaultValues={{ items: [...] }} onValidSubmit={save}>
  <FieldArray name="items" label="Items" sortable duplicable min={1} max={6} emptyItem={{ quantity: 1 }} addLabel="Add item">
    {(row) => (
      <>
        <TextField label="Product" name={row.name("name")} />
        <NumberField label="Quantity" name={row.name("quantity")} />
      </>
    )}
  </FieldArray>
  <SubmitButton>Save</SubmitButton>
</Form>

Events

  1. Events appear here when you interact with the preview.

Single-value rows (phones), plain appearance

Phones

Nested arrays: sections and their items

Sections
  • Items

Import

import { FieldArray, useFieldArray } from "@yasinsensoy/web";

FieldArray

componentClient component

Repeating form rows with a ready-made look: title, rows, remove / duplicate buttons, drag to reorder (sortable), add button, empty state and the array's error. The logic is the same as useFieldArray.

  • When a row is added its first field is focused; when removed, focus moves to the next row (or the add button if none). Both are announced to screen readers.
  • min/max lock the buttons automatically; when full, the add button's tooltip says why.
  • With sortable rows are dragged by the handle; on the keyboard focus the handle and use Space + arrow keys or Alt + arrow.
FieldArray({ name, defaultValue, emptyItem, min, max, focusOnAdd, label, description, children, sortable, removable, duplicable, addLabel, footer, empty, rowLabel, rowVariant, rowClassName, className, disabled, ...props }: FieldArrayProps<T>): JSX.Element

Examples

const Invoice = z.object({
  items: z
    .array(z.object({ name: z.string().min(1, "Enter a product name"), quantity: z.number().min(1) }))
    .min(1, "Add at least one item"),
});

<Form schema={Invoice} defaultValues={{ items: [{ name: "Pen", quantity: 2 }] }}
  onValidSubmit={(data) => save(data)}>
  <FieldArray name="items" label="Items" emptyItem={{ quantity: 1 }} sortable
    duplicable addLabel="Add item" max={20}>
    {(row) => (
      <div className="grid gap-3 sm:grid-cols-[1fr_8rem]">
        <TextField label="Product" name={row.name("name")} />
        <NumberField label="Quantity" name={row.name("quantity")} />
      </div>
    )}
  </FieldArray>
  <SubmitButton>Save</SubmitButton>
</Form>

Repeating rows inside a Form (invoice items, phone numbers, education history…): adds, removes, moves and duplicates rows.

  • Fields are uncontrolled as usual; when row order changes, the typed values move with the row and the form does not re-render.
  • Row field names become row.name("name") → items[0].name; Form turns them into an array, and Zod schema errors (items[1].quantity) appear under the matching field.
  • Initial rows come from Form defaultValues (and the draft); the fields of an added row are filled with the given value.
  • Even with no rows left the value is sent as [], and a row with all fields left empty as {} (indexes don't shift).
  • Rows return to their initial state when the form is reset.

For a ready-made look (title, add/remove buttons, drag to reorder, error, empty state) use FieldArray; this hook is for your own layout.

useFieldArray(options: UseFieldArrayOptions<T>): FieldArrayApi<T>

Examples

function Items() {
  const items = useFieldArray({ name: "items", emptyItem: { quantity: 1 }, min: 1 });
  return (
    <>
      {items.fields.map((row) => (
        <div key={row.key} className="flex gap-2">
          <TextField label="Product" name={row.name("name")} required />
          <NumberField label="Quantity" name={row.name("quantity")} />
          <IconButton icon="trash" label="Remove" onClick={() => items.remove(row.index)}
            disabled={!items.canRemove} />
        </div>
      ))}
      <Button onClick={() => items.append()}>Add item</Button>
    </>
  );
}

useFieldArray options.

NameTypeDefaultDescription
namestringField name of the array ("items"). Names of the fields in rows are generated with row.name("name") as items[0].name; Form turns them into an array on submit, and schema errors come back under the same name. For nested arrays use the parent row's name: row.name("features").
defaultValue?readonly T[]Initial rows. If omitted, the array in the nearest Form's defaultValues (or in a restored draft) is used.
emptyItem?T | (() => T){}Initial value of a new row (e.g. { quantity: 1 }); a function is called on each add. If rows are single values (tags[0]), give a string: "".
min?number0Minimum number of rows. If there are fewer initially, empty rows are added; at this count rows cannot be removed. To show the message of a rule like "at least one item", also give min in the schema.
max?numberMaximum number of rows; nothing can be added when full.
focusOnAdd?booleantrueFocuses the first field inside a row when it is added.

FieldArrayRow

interface

An item of useFieldArray fields: one row.

NameTypeDescription
keystringStable key of the row; pass it as key (not the index).
indexnumberCurrent index of the row (from 0).
name(path?: string) => stringName of a field in the row: row.name("name") → "items[0].name", nested row.name("address.city") → "items[0].address.city". Without an argument, the row's own name ("items[0]"; for single-value rows).
defaultValueT | undefinedInitial value of the row (given on add or from defaultValues). Fields already read it themselves; this is for your own controlled component.
errorstring | undefinedError of the row itself (e.g. the refine of the row object in the schema: "End must be after start"). Field errors appear under the fields.

useFieldArray add options.

NameTypeDefaultDescription
focus?booleanfocusOnAddFocus the first field of the new row.

FieldArrayApi

interface

Result of useFieldArray.

NameTypeDescription
namestringName of the array.
fieldsFieldArrayRow<T>[]Rows, in order. See FieldArrayRow.
lengthnumberNumber of rows.
append(value?: T, options?: FieldArrayAddOptions) => voidAppends a row at the end. If no value is given, emptyItem.
prepend(value?: T, options?: FieldArrayAddOptions) => voidPrepends a row at the start.
insert(index: number, value?: T, options?: FieldArrayAddOptions) => voidInserts a row at position index.
remove(index: number | readonly number[]) => voidRemoves the row (or rows); does not go below min.
move(from: number, to: number) => voidMoves a row from from to to; typed values move with the row.
swap(a: number, b: number) => voidSwaps two rows.
duplicate(index: number, options?: FieldArrayAddOptions) => voidCopies the row, with its current typed values, right below it.
replace(values: readonly T[]) => voidReplaces all rows with the given ones (fields are rebuilt with these values).
getValues() => T[]Current values of the rows in the form (converted to their types if there is a schema). Outside a form, the rows' initial values are returned.
canAddbooleanmax has not been reached.
canRemovebooleanAbove min.
errorstring | undefinedError of the array itself (e.g. z.array(...).min(1, "Add at least one item") in the schema) or a server error. A schema error appears once the user adds/removes rows or tries to submit.

Props of the FieldArray component.

Extends: Omit<ComponentProps<"fieldset">, "children" | "name" | "defaultValue">

NameTypeDefaultDescription
label?ReactNodeTitle of the group (<legend>).
description?ReactNodeDescription under the title.
children(row: FieldArrayRow<T>, array: FieldArrayApi<T>) => ReactNodeFields of a row. Give field names with row.name("name"). The second argument is the whole array (e.g. for a "Move up" button in the row). The row is a container query (@container) box: size columns by the row's width, not the screen (grid @md:grid-cols-[1fr_8rem]); it doesn't overflow in a narrow panel either.
sortable?booleanRows are reordered by dragging the handle (mouse, touch, keyboard). See SortableList.
removable?booleantrueRow remove button.
duplicable?booleanButton that copies the row with its typed values.
addLabel?ReactNode"Ekle"Text of the add button.
footer?false | ((array: FieldArrayApi<T>) => ReactNode)Your own footer instead of the add button (e.g. buttons adding a few preset rows). With false the add button is hidden.
empty?ReactNode"Henüz satır yok"Content shown when there are no rows.
rowLabel?(row: FieldArrayRow<T>) => string"{sıra}. satır"Readable name of the row: used in the remove button's name and screen reader announcements (e.g. (row) => \Item ${row.index + 1}\``).
rowVariant?"card" | "plain""card"Look of the rows: card is a bordered box, plain just the rows.
rowClassName?stringClass of the row box.
namestringField name of the array ("items"). Names of the fields in rows are generated with row.name("name") as items[0].name; Form turns them into an array on submit, and schema errors come back under the same name. For nested arrays use the parent row's name: row.name("features").
defaultValue?readonly T[]Initial rows. If omitted, the array in the nearest Form's defaultValues (or in a restored draft) is used.
emptyItem?T | (() => T){}Initial value of a new row (e.g. { quantity: 1 }); a function is called on each add. If rows are single values (tags[0]), give a string: "".
min?number0Minimum number of rows. If there are fewer initially, empty rows are added; at this count rows cannot be removed. To show the message of a rule like "at least one item", also give min in the schema.
max?numberMaximum number of rows; nothing can be added when full.
focusOnAdd?booleantrueFocuses the first field inside a row when it is added.