---
title: ForEach
description: Repeat components for each item in a data list.
icon: repeat
---

import { ComponentPreview } from '/snippets/component-preview.mdx'

`ForEach` is a control-flow component that iterates over a list in your data, rendering its children once per item. Each iteration receives the list item as the interpolation context, so `{{ field }}` placeholders resolve to that item's values.

## Basic Usage

<ComponentPreview json={{"view":{"cssClass":"gap-2","type":"Column","children":[{"type":"ForEach","key":"crew","children":[{"type":"Card","children":[{"type":"CardHeader","children":[{"cssClass":"gap-2 items-center","type":"Row","children":[{"type":"CardTitle","content":"{{ name }}"},{"type":"Badge","label":"{{ designation }}","variant":"secondary"}]},{"type":"CardDescription","content":"{{ email }}"}]}]}]}]},"state":{"crew":[{"name":"Arthur Dent","designation":"Sandwich Maker","email":"arthur@heart-of-gold.ship"},{"name":"Ford Prefect","designation":"Researcher","email":"ford@megadodo.pub"},{"name":"Trillian","designation":"Astrophysicist","email":"trillian@heart-of-gold.ship"}]}}} playground=" ">
<CodeGroup>
```python Python icon="python"
from prefab_ui.app import set_initial_state
from prefab_ui.components import (
    Card,
    CardHeader,
    CardTitle,
    CardDescription,
    Badge,
    Column,
    Row,
)
from prefab_ui.components.control_flow import ForEach

set_initial_state(crew=[
    {"name": "Arthur Dent", "designation": "Sandwich Maker", "email": "arthur@heart-of-gold.ship"},
    {"name": "Ford Prefect", "designation": "Researcher", "email": "ford@megadodo.pub"},
    {"name": "Trillian", "designation": "Astrophysicist", "email": "trillian@heart-of-gold.ship"},
])

with Column(gap=2):
    with ForEach("crew"):
        with Card():
            with CardHeader():
                with Row(gap=2, align="center"):
                    CardTitle("{{ name }}")
                    Badge("{{ designation }}", variant="secondary")
                CardDescription("{{ email }}")
```
```json Protocol icon="brackets-curly"
{
  "view": {
    "cssClass": "gap-2",
    "type": "Column",
    "children": [
      {
        "type": "ForEach",
        "key": "crew",
        "children": [
          {
            "type": "Card",
            "children": [
              {
                "type": "CardHeader",
                "children": [
                  {
                    "cssClass": "gap-2 items-center",
                    "type": "Row",
                    "children": [
                      {"type": "CardTitle", "content": "{{ name }}"},
                      {"type": "Badge", "label": "{{ designation }}", "variant": "secondary"}
                    ]
                  },
                  {"type": "CardDescription", "content": "{{ email }}"}
                ]
              }
            ]
          }
        ]
      }
    ]
  },
  "state": {
    "crew": [
      {
        "name": "Arthur Dent",
        "designation": "Sandwich Maker",
        "email": "arthur@heart-of-gold.ship"
      },
      {
        "name": "Ford Prefect",
        "designation": "Researcher",
        "email": "ford@megadodo.pub"
      },
      {
        "name": "Trillian",
        "designation": "Astrophysicist",
        "email": "trillian@heart-of-gold.ship"
      }
    ]
  }
}
```
</CodeGroup>
</ComponentPreview>

When rendered with the data above, this produces one card per crew member.

## How It Works

The `key` argument (passed positionally or as a keyword) names the field in the data dict that contains the list. At render time, `ForEach` iterates that list. If each item is a dict, its keys become the interpolation context for that iteration. If an item is a scalar, it's available as `{{ $item }}`.

<ComponentPreview json={{"view":{"cssClass":"gap-2","type":"Row","children":[{"type":"ForEach","key":"tags","children":[{"type":"Badge","label":"{{ $item }}","variant":"secondary"}]}]},"state":{"tags":["earth","magrathea","vogon poetry","42"]}}} playground="ZnJvbSBwcmVmYWJfdWkuYXBwIGltcG9ydCBzZXRfaW5pdGlhbF9zdGF0ZQpmcm9tIHByZWZhYl91aS5jb21wb25lbnRzIGltcG9ydCBCYWRnZSwgUm93CmZyb20gcHJlZmFiX3VpLmNvbXBvbmVudHMuY29udHJvbF9mbG93IGltcG9ydCBGb3JFYWNoCgpzZXRfaW5pdGlhbF9zdGF0ZSh0YWdzPVsiZWFydGgiLCAibWFncmF0aGVhIiwgInZvZ29uIHBvZXRyeSIsICI0MiJdKQoKd2l0aCBSb3coZ2FwPTIpOgogICAgd2l0aCBGb3JFYWNoKCJ0YWdzIik6CiAgICAgICAgQmFkZ2UoInt7ICRpdGVtIH19IiwgdmFyaWFudD0ic2Vjb25kYXJ5IikK">
<CodeGroup>
```python Python icon="python"
from prefab_ui.app import set_initial_state
from prefab_ui.components import Badge, Row
from prefab_ui.components.control_flow import ForEach

set_initial_state(tags=["earth", "magrathea", "vogon poetry", "42"])

with Row(gap=2):
    with ForEach("tags"):
        Badge("{{ $item }}", variant="secondary")
```
```json Protocol icon="brackets-curly"
{
  "view": {
    "cssClass": "gap-2",
    "type": "Row",
    "children": [
      {
        "type": "ForEach",
        "key": "tags",
        "children": [{"type": "Badge", "label": "{{ $item }}", "variant": "secondary"}]
      }
    ]
  },
  "state": {"tags": ["earth", "magrathea", "vogon poetry", "42"]}
}
```
</CodeGroup>
</ComponentPreview>

With `{"tags": ["earth", "magrathea", "vogon poetry", "42"]}`, this renders one badge per item.

## Iteration Variables

Beyond the item's own fields, every iteration exposes two special variables: `$index` (zero-based position) and `$item` (the entire current item). Individual fields like `{{ name }}` are still available directly — `$item` is for when you need to pass the whole object somewhere, like an action argument.

<ComponentPreview json={{"view":{"cssClass":"gap-1","type":"Column","children":[{"type":"ForEach","key":"steps","children":[{"content":"{{ $index + 1 }}. {{ $item }}","type":"Text"}]}]},"state":{"steps":["Collect underpants","?","Profit"]}}} playground="ZnJvbSBwcmVmYWJfdWkuYXBwIGltcG9ydCBzZXRfaW5pdGlhbF9zdGF0ZQpmcm9tIHByZWZhYl91aS5jb21wb25lbnRzIGltcG9ydCBDb2x1bW4sIFRleHQKZnJvbSBwcmVmYWJfdWkuY29tcG9uZW50cy5jb250cm9sX2Zsb3cgaW1wb3J0IEZvckVhY2gKCnNldF9pbml0aWFsX3N0YXRlKHN0ZXBzPVsiQ29sbGVjdCB1bmRlcnBhbnRzIiwgIj8iLCAiUHJvZml0Il0pCgp3aXRoIENvbHVtbihnYXA9MSk6CiAgICB3aXRoIEZvckVhY2goInN0ZXBzIik6CiAgICAgICAgVGV4dCgie3sgJGluZGV4ICsgMSB9fS4ge3sgJGl0ZW0gfX0iKQo=">
<CodeGroup>
```python Python icon="python"
from prefab_ui.app import set_initial_state
from prefab_ui.components import Column, Text
from prefab_ui.components.control_flow import ForEach

set_initial_state(steps=["Collect underpants", "?", "Profit"])

with Column(gap=1):
    with ForEach("steps"):
        Text("{{ $index + 1 }}. {{ $item }}")
```
```json Protocol icon="brackets-curly"
{
  "view": {
    "cssClass": "gap-1",
    "type": "Column",
    "children": [
      {
        "type": "ForEach",
        "key": "steps",
        "children": [{"content": "{{ $index + 1 }}. {{ $item }}", "type": "Text"}]
      }
    ]
  },
  "state": {"steps": ["Collect underpants", "?", "Profit"]}
}
```
</CodeGroup>
</ComponentPreview>

`$index` is especially useful for actions that target a specific list position — `SetState("items.{{ $index }}.done", true)` updates the `done` field of the current item. And `$item` lets you pass the whole object to actions like `CallTool("edit_user", arguments={"user": "{{ $item }}"})`.

## Nested Data

Since each item becomes the full interpolation context for that iteration, you can access nested fields with dot notation:

<ComponentPreview json={{"view":{"cssClass":"gap-2","type":"Column","children":[{"type":"ForEach","key":"projects","children":[{"type":"Card","children":[{"type":"CardHeader","children":[{"type":"CardTitle","content":"{{ name }}"},{"type":"CardDescription","content":"Owner: {{ owner.name }}"}]}]}]}]},"state":{"projects":[{"name":"Heart of Gold","owner":{"name":"Zaphod Beeblebrox"}},{"name":"Hitchhiker's Guide","owner":{"name":"Ford Prefect"}}]}}} playground=" ">
<CodeGroup>
```python Python icon="python"
from prefab_ui.app import set_initial_state
from prefab_ui.components import (
    Card,
    CardHeader,
    CardTitle,
    CardDescription,
    Column,
)
from prefab_ui.components.control_flow import ForEach

set_initial_state(projects=[
    {"name": "Heart of Gold", "owner": {"name": "Zaphod Beeblebrox"}},
    {"name": "Hitchhiker's Guide", "owner": {"name": "Ford Prefect"}},
])

with Column(gap=2):
    with ForEach("projects"):
        with Card():
            with CardHeader():
                CardTitle("{{ name }}")
                CardDescription("Owner: {{ owner.name }}")
```
```json Protocol icon="brackets-curly"
{
  "view": {
    "cssClass": "gap-2",
    "type": "Column",
    "children": [
      {
        "type": "ForEach",
        "key": "projects",
        "children": [
          {
            "type": "Card",
            "children": [
              {
                "type": "CardHeader",
                "children": [
                  {"type": "CardTitle", "content": "{{ name }}"},
                  {"type": "CardDescription", "content": "Owner: {{ owner.name }}"}
                ]
              }
            ]
          }
        ]
      }
    ]
  },
  "state": {
    "projects": [
      {"name": "Heart of Gold", "owner": {"name": "Zaphod Beeblebrox"}},
      {"name": "Hitchhiker's Guide", "owner": {"name": "Ford Prefect"}}
    ]
  }
}
```
</CodeGroup>
</ComponentPreview>

## API Reference

<Card icon="code" title="ForEach Parameters">
<ParamField body="key" type="str" required>
  The data field containing the list to iterate over. Can be passed as a positional argument.
</ParamField>

<ParamField body="css_class" type="str | None" default="None">
  Additional Tailwind CSS classes for the wrapper element.
</ParamField>
</Card>

## Protocol Reference

```json ForEach
{
  "type": "ForEach",
  "children?": "[Component]",
  "let?": "object",
  "key": "string (required)",
  "cssClass?": "string"
}
```

For the complete protocol schema, see [ForEach](/protocol/for-each).
