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.

red

green

blue

yellow

orange

purple

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 can be accessed as list of key-value pairs. 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. Assuming we want to display a dictionary of secondary colors as keys and their constituent primary colors as values, we can modify the code as below:

purple

red

blue

orange

yellow

red

green

blue

yellow

Expand

API Reference

rx.foreach

A component that takes in an iterable and a render function and renders a list of components.

Props

PropTypeDescription
iterable
Iterable

The iterable to create components from.

Built with Reflex