For AI agents: the complete documentation index is at llms.txt. Markdown versions are available by appending .md or sending Accept: text/markdown.
Reflex Logo
Docs Logo
Library

/

Dynamic Rendering

/

Foreach

Foreach

The rx.foreach component takes an iterable (list, tuple, or dict) and a function that renders each item in the list. This is useful for dynamically rendering a list of items defined in a state.

Use rx.foreach for state vars; use Python list or dict comprehensions for constants.

#E5484D

#12A594

#3E63DD

#AD5700

#F76B15

#8E4EC6

Expand

The function can also take an index as a second argument.

0

1

2

3

4

5

Nested foreach components can be used to render nested lists.

When indexing into a nested list, it's important to declare the list's type as Reflex requires it for type checking. This ensures that any potential frontend JS errors are caught before the user can encounter them.

1
2
3
4
5
6
7
8
9
Expand

Below is a more complex example of foreach within a todo list.

Todos

  1. Write Code

  2. Sleep

  3. Have Fun

Expand

Dictionaries

Items in a dictionary are passed to the render function as key-value pairs. When iterating over a dict, keys are coerced to strings in the foreach callback, even when the Python dictionary uses another key type. Using the color example, we can slightly modify the code to use dicts as shown below.

1

2

3

Now let's show a more complex example with dicts using the color example. This example groups related hex colors in a dictionary and renders both the keys and values as swatches:

#8E4EC6

#E5484D

#3E63DD

#F76B15

#AD5700

#E5484D

#12A594

#3E63DD

#AD5700

Expand

API Reference

rx.foreach

  • iterable: A state var or iterable to render. Lists, tuples, sets, strings, and dicts are supported; dicts are passed to render_fn as key-value tuples with string keys.
  • render_fn: A function that returns a component for each item. It receives the item as the first rx.Var[...] argument and, optionally, the index as a second rx.Var[int] argument.
Built with Reflex