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.
rx.foreach for state vars; use Python list or dict comprehensions for constants.#E5484D
#12A594
#3E63DD
#AD5700
#F76B15
#8E4EC6
ExpandCollapse
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.
ExpandCollapse
Below is a more complex example of foreach within a todo list.
Todos
Write Code
Sleep
Have Fun
ExpandCollapse
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
ExpandCollapse
API Reference
rx.foreach
iterable: A state var or iterable to render. Lists, tuples, sets, strings, and dicts are supported; dicts are passed torender_fnas key-value tuples with string keys.render_fn: A function that returns a component for each item. It receives the item as the firstrx.Var[...]argument and, optionally, the index as a secondrx.Var[int]argument.