# Repeater

> A Repeater widget to allow the user to enter information as a list

Repeater widgets are [Input Fields](https://golemui.com/dx/widgets-reference/input-fields/overview.md) that allow the user to enter information as a list given a template. The information will be stored and returned as an array of objects.


```ts title="repeater.ts"

export default [
  gui.inputs.repeater('guests', {
    addLabel: 'Add Guest',
    removeLabel: 'Remove Guest',
    label: 'Guest List',
    template: [
      gui.layouts.grid([
        gui.inputs.textInput('guests.items.guest_name', {
          label: 'Full Name',
        }),
      ]),
    ],
  }),
];
```

_Live demo on the docs page. Form definition: [repeater.ts](https://golemui.com/template/widgets-dx/repeater/repeater.ts)._

## Props

Use this `props` to customize your Repeater widget.

| prop               | type   | description                                                               |
| ------------------ | ------ | ------------------------------------------------------------------------- |
| `template`         | object | **MANDATORY** A template Field with the elements rendered by the repeater |
| `addButtonIcon`    | string | CSS class string for the icon displayed in the add button                 |
| `addLabel`         | string | Label text for the add button                                             |
| `removeButtonIcon` | string | CSS class string for the icon displayed in the remove button              |
| `removeLabel`      | string | Label text for the remove button                                          |
| `title`            | string | Optional title displayed at the top of each card                          |

### Template

Use the property `template` to render a tree of Field widgets for each item in the array of the Repeater widget. The `path` in the [Input Fields](https://golemui.com/dx/widgets-reference/input-fields/overview.md) widgets inside the `template` will be updated replacing `items` keyword by the index of the array. For example, `users.items.firstName` will be replaced by `users[0].firstName` for the first element and so on.


```ts title="repeater.ts"

export default [
  gui.inputs.repeater('guests', {
    addLabel: 'Add Guest',
    removeLabel: 'Remove Guest',
    label: 'Guest List',
    template: [
      gui.layouts.grid([
        gui.inputs.textInput('guests.items.guest_name', {
          label: 'Full Name',
        }),
      ]),
    ],
  }),
];
```

_Live demo on the docs page. Form definition: [repeater.ts](https://golemui.com/template/widgets-dx/repeater/repeater.ts)._

### Add and Remove Labels

Use the property `addLabel` and `removeLabel` to set custom labels for the Add and Remove button.


```ts title="repeater.ts"

export default [
  gui.inputs.repeater('users', {
    addLabel: 'Add new developer',
    removeLabel: 'Remove developer',
    defaultValue: [
      {
        firstName: 'John',
        lastName: 'Doe',
      },
      {
        firstName: 'Jane',
        lastName: 'Doe',
      },
    ],
    template: [
      gui.layouts.grid([
        gui.inputs.textInput('users.items.firstName'),
        gui.inputs.textInput('users.items.lastName'),
      ]),
    ],
  }),
];
```

_Live demo on the docs page. Form definition: [repeater-labels.ts](https://golemui.com/template/widgets-dx/repeater/repeater-labels.ts)._

### Max items

Use the array validator's `maxItems` to cap the number of rows. The Add button stays enabled, so the user can add a row past the cap and then remove another one. Past the cap the form is invalid, and the repeater shows the `maxItems` error when validation runs. With the default [`validateOn`](https://golemui.com/dx/features/validators.md#configuring-when-validation-triggers), that is when the user adds the row.


```ts title="repeater.ts"

export default [
  gui.inputs.repeater('contacts', {
    addLabel: 'Add Contact',
    removeLabel: 'Delete',
    label: 'Emergency Contacts',
    validator: {
      maxItems: 3,
      messages: {
        maxItems: 'Add at most 3 contacts',
      },
    },
    uid: 'repeater_limit',
    template: [
      gui.layouts.grid([
        gui.inputs.textInput('contacts.items.phone', {
          label: 'Phone Number',
        }),
      ]),
    ],
  }),
];
```

_Live demo on the docs page. Form definition: [repeater-limit.ts](https://golemui.com/template/widgets-dx/repeater/repeater-limit.ts)._

### Card Title

Use the property `title` to display a static title at the top of each card.


```ts title="repeater.ts"

export default [
  gui.inputs.repeater('guests', {
    title: 'Guest',
    addLabel: 'Add Guest',
    removeLabel: 'Remove',
    label: 'Guest List',
    uid: 'repeater_title',
    template: [
      gui.layouts.grid([
        gui.inputs.textInput('guests.items.guest_name', {
          label: 'Full Name',
        }),
      ]),
    ],
  }),
];
```

_Live demo on the docs page. Form definition: [repeater-title.ts](https://golemui.com/template/widgets-dx/repeater/repeater-title.ts)._

### Button Icons

Use the properties `addButtonIcon` and `removeButtonIcon` to display an icon inside the add and remove buttons. Icons are passed as a CSS class string, the same way as other icon props in the library.


```ts title="repeater.ts"

export default [
  gui.inputs.repeater('guests', {
    addLabel: 'Add Guest',
    removeLabel: 'Remove',
    addButtonIcon: 'add',
    removeButtonIcon: 'remove',
    label: 'Guest List',
    uid: 'repeater_icons',
    template: [
      gui.layouts.grid([
        gui.inputs.textInput('guests.items.guest_name', {
          label: 'Full Name',
        }),
      ]),
    ],
  }),
];
```

_Live demo on the docs page. Form definition: [repeater-icons.ts](https://golemui.com/template/widgets-dx/repeater/repeater-icons.ts)._

### Nested Repeaters

Repeaters can be nested inside other repeaters to model hierarchical data structures. Each nesting level adds an additional `.items.` segment to the `path`. For example, in a Teams → Members structure:

- The outer repeater path is `teams`
- Fields inside the outer template use `teams.items.fieldName`
- The inner repeater path is `teams.items.members`
- Fields inside the inner template use `teams.items.members.items.fieldName`

At runtime, each `items` token is replaced by the corresponding array index. For instance, `teams.items.members.items.memberName` becomes `teams[0].members[1].memberName` for the second member of the first team.


```ts title="repeater.ts"

export default [
  gui.inputs.repeater('teams', {
    addLabel: 'Add Team',
    removeLabel: 'Remove Team',
    label: 'Teams',
    uid: 'team_repeater',
    template: [
      gui.layouts.grid([
        gui.inputs.textInput('teams.items.teamName', {
          label: 'Team Name',
        }),
        gui.inputs.repeater('teams.items.members', {
          addLabel: 'Add Member',
          removeLabel: 'Remove Member',
          label: 'Members',
          uid: 'member_repeater',
          template: [
            gui.layouts.grid([
              gui.inputs.textInput('teams.items.members.items.memberName', {
                label: 'Member Name',
              }),
            ]),
          ],
        }),
      ]),
    ],
  }),
];
```

_Live demo on the docs page. Form definition: [repeater-nested.ts](https://golemui.com/template/widgets-dx/repeater/repeater-nested.ts)._

For the `$item`/`$index` scope variables available inside nested templates, see [`$item` and `$index`](#item-and-index) below.

### `$item` and `$index`

Inside a repeater's `template`, every widget can read the current row through two scope variables: `$item` (the row's array element, looked up live from form data) and `$index` (its zero-based position). Both are available in `include`/`exclude`/`disabled`/`readonly` `when` expressions, in `{{ }}` interpolation slots, and in i18n `params` - anywhere those mechanisms already work, they just gain two more variables to read from.


```ts title="repeater.ts"

export default [
  gui.inputs.repeater('lineItems', {
    addLabel: 'Add Line Item',
    removeLabel: 'Remove Line Item',
    label: 'Line Items',
    uid: 'line_items_repeater',
    template: [
      gui.layouts.grid([
        gui.inputs.numberInput('lineItems.items.quantity', {
          label: 'Quantity',
        }),
        gui.inputs.currency('lineItems.items.unitPrice', {
          label: 'Unit Price',
        }),
        gui.displays.markdownText({
          md: 'Row {{ $index + 1 }} total: {{ (($item.quantity ?? 0) * ($item.unitPrice ?? 0)).toFixed(2) }}',
          include: {
            when: '$item.quantity !== undefined',
          },
        }),
      ]),
    ],
  }),
];
```

_Live demo on the docs page. Form definition: [repeater-item-index.ts](https://golemui.com/template/widgets-dx/repeater/repeater-item-index.ts)._

A freshly added row has no data yet, so `$item` leaf values can be `undefined` - guard reads with `??` or `?.`, as in `$item.quantity ?? 0`. `$index` is always a defined number and never needs a guard.

Where you can use `$item`/`$index`:

- [Inline `when`](https://golemui.com/dx/features/states/inline-when.md) - `include`, `exclude`, `disabled`, and `readonly`
- [String interpolation](https://golemui.com/dx/features/string-interpolation.md) - `{{ }}` slots in any string prop
- [i18n dynamic params](https://golemui.com/dx/features/i18n.md#dynamic-params) - bare-expression `params` values

### Scope in nested repeaters

For nested repeaters, `$item`/`$index` always resolve to the **innermost** enclosing repeater's item. A widget placed directly in an _outer_ template - not inside the inner repeater's template - sees the _outer_ item instead. Scope follows where a widget sits in the template tree, not "the deepest repeater anywhere in the form."


```ts title="repeater.ts"

export default [
  gui.inputs.repeater('projects', {
    addLabel: 'Add Project',
    removeLabel: 'Remove Project',
    label: 'Projects',
    uid: 'projects_repeater',
    template: [
      gui.layouts.grid([
        gui.inputs.textInput('projects.items.projectName', {
          label: 'Project Name',
        }),
        gui.inputs.repeater('projects.items.tasks', {
          addLabel: 'Add Task',
          removeLabel: 'Remove Task',
          label: 'Tasks',
          uid: 'tasks_repeater',
          template: [
            gui.layouts.grid([
              gui.inputs.numberInput('projects.items.tasks.items.hours', {
                label: 'Hours',
              }),
              gui.inputs.currency('projects.items.tasks.items.rate', {
                label: 'Hourly Rate',
              }),
              gui.displays.markdownText({
                md: 'Task {{ $index + 1 }}: {{ (($item.hours ?? 0) * ($item.rate ?? 0)).toFixed(2) }}',
              }),
            ]),
          ],
        }),
        gui.displays.alert({
          text: 'Project total: {{ ($item.tasks ?? []).reduce((sum, task) => sum + ((task.hours ?? 0) * (task.rate ?? 0)), 0).toFixed(2) }}',
        }),
      ]),
    ],
  }),
];
```

_Live demo on the docs page. Form definition: [repeater-item-index-nested.ts](https://golemui.com/template/widgets-dx/repeater/repeater-item-index-nested.ts)._

<Aside>
To reach an *outer* row's data from inside the inner template's `when` expression, use the `items` path token described above, e.g. `$form.teams.items.teamName`. This only applies to `when` expressions - `{{ }}` interpolation and i18n `params` do not rewrite `items` tokens, so read the outer row through `$item` at the level where it is in scope instead.
</Aside>

<Aside type="caution">
Named states declared in `formConfig.states` do **not** receive `$item`/`$index` - only per-widget `when`, `{{ }}` interpolation, and i18n `params` on widgets that live inside a repeater `template` get this scope.
</Aside>

### Events from a row

An event from a widget inside a row, such as the `click` of a menu or the `change` of a field, carries the row it came from in `event.row`, so one handler serves every row:

- `index`: the row's position in its repeater, the same value as `$index`.
- `indexes`: the position in every enclosing repeater, outermost first. Its last entry is `index`.
- `path`: the data path of the row, such as `team.1`, or `teams.2.members.1` in a nested repeater.

Outside a repeater, `row` is `undefined`. Pick an action in the menu of a row below: the handler reads the row's data with `event.row.index`.


```ts title="repeater.ts"

export default [
  gui.inputs.repeater('team', {
    addLabel: 'Add member',
    removeLabel: 'Remove member',
    label: 'Team',
    uid: 'team_repeater',
    template: [
      gui.layouts.grid([
        gui.inputs.textInput('team.items.name', {
          label: 'Name',
          size: 5,
        }),
        gui.actions.menu({
          items: [
            {
              label: 'Make lead',
              value: 'lead',
            },
            {
              label: 'Send invite',
              value: 'invite',
            },
          ],
          ariaLabel: 'Member actions',
          icon: 'more_vert',
          variant: 'outlined',
          placement: 'bottom-end',
          uid: 'memberMenu',
          onClick: () => 'repeaterRowAction',
        }),
      ], {
        direction: 'row',
      }),
    ],
  }),
  gui.displays.alert({
    text: 'Pick an action in the menu of a row.',
    uid: 'rowActionResult',
  }),
];
```

_Live demo on the docs page. Form definition: [repeater-row-events.ts](https://golemui.com/template/widgets-dx/repeater/repeater-row-events.ts), data: [repeater-row-events.data.json](https://golemui.com/template/widgets/repeater/repeater-row-events.data.json)._

```ts title="Handling the row event"
function onFormEvent(event: FormEvent) {
  if (event.name !== 'repeaterRowAction' || !event.row) return;
  const member = event.data.team[event.row.index];
  console.log(event.detail.value, member.name, event.row.path);
}
```

Read `row` in your `formEvent` handler, in a menu's `onClick: (event) => ...`, or in an input's `onChange: (event) => ...`. A button's `onClick` receives only the form data: return an event name instead, `onClick: () => 'rowPicked'`, and read `event.row` in `formEvent`.

<Aside>
For options that depend on a row's data, such as the cities of the country picked in that row, use a definition callback that reads `$item`, not `event.update` from a row event. An override moves with its row when the Remove button removes a row, but it stays at its position when `setData` writes a new array, so a row can then show the options of another row. `gui.inputs.dropdown('users.items.city', ({ $item }) => ({ label: 'City', items: citiesOf($item?.country) }))` follows each row.

Read `$item` with `?.` in a definition callback. The form calls the callback once without a row when it builds the form, and a callback that throws gives [`formHealth` code 22](https://golemui.com/dx/integration/configuration.md#formhealth).

</Aside>

### State of a row

A row has state besides its data: its touched state, its errors, the issues your app injects, and the prop overrides your app sets by path. This state belongs to the item in the row, not to its position.

When the user removes a row with the Remove button, the state of the other rows moves with them, also in nested repeaters. Two cases stay at their positions:

- `setData` with a new array. The form can't know which new row was which old row.
- An error that a widget reports itself, such as a rejected date like 02/31/2026. The rejected text stays in the input at that position, so its error stays next to it.

## Deprecated props

This prop still works, and v3.0.0 removes it:

| Deprecated | Use instead                                                                                       |
| ---------- | ------------------------------------------------------------------------------------------------- |
| `limit`    | `validator.maxItems`. `limit` disables the Add button at that number of rows and shows no message |

## Styling

Repeaters can be styled as explained in the [Styling Guide](https://golemui.com/dx/styling/overview.md).

### CSS Variables

Following you will find a list with the CSS Variables and a quick description of what you will style.

| CSS Variable         | Description                         |
| -------------------- | ----------------------------------- |
| `--gui-space-gap`    | Space between each repeater element |
| `--gui-field-gap`    | Space between Add/Remove buttons    |
| `--gui-padding`      | Repeater element padding            |
| `--gui-color-border` | Repeater element border color       |
| `--gui-radius`       | Repeater element border radius      |
| `--gui-color-bg`     | Repeater element background color   |
| `--gui-color-fg`     | Repeater element text color         |

### Anatomy

This is the anatomy of the Repeater Widget in case you want to use your CSS styles.


```html title="repeater.html"
<gui-repeater-input class="gui-repeater gui-field">
  <div id="repeater_uid" class="gui-repeater__main-card gui-repeater__card">
    <gui-label>
      <span class="gui-label" id="repeater_uid_label">
        <span class="gui-label__text">Guest List</span>
      </span>
    </gui-label>

    <div class="gui-repeater__card">
      <div class="gui-repeater__card-header">
        <span class="gui-repeater__card-title">Guest 1</span>
        <button
          type="button"
          tabindex="0"
          class="gui-button gui-button--sm gui-repeater__remove-btn"
        >
          <span class="gui-widget-icon gui-button-icon delete" data-icon="delete"></span>
          Remove Guest
        </button>
      </div>
      <gui-grid-layout class="gui-field">
        <div class="gui-grid" id="#0.0.t[0]">
          <div class="gui-grid__cell">
            <!-- Child widget: Full Name -->
          </div>
        </div>
      </gui-grid-layout>
    </div>

    <button type="button" tabindex="0" class="gui-button gui-repeater__add-btn">
      <span class="gui-widget-icon gui-button-icon person_add" data-icon="person_add"></span>
      Add Guest
    </button>
  </div>
</gui-repeater-input>
```
