reflex-dev/reflex · error · ValueError

The render function must return a component.

Error message

The render function must return a component.

What it means

The render function passed to `rx.foreach` (IterTag) returned something that is not a component after normalization — `None`, a raw string/number, or a value `_into_component_once` cannot convert.

Source

Thrown at packages/reflex-base/src/reflex_base/components/tags/iter_tag.py:111

        if len(args) == 1:
            # If the render function doesn't take the index as an argument.
            component = self.render_fn(arg)
        else:
            # If the render function takes the index as an argument.
            if len(args) != 2:
                msg = "The render function must take 2 arguments."
                raise ValueError(msg)
            component = self.render_fn(arg, index)

        # Nested foreach components or cond must be wrapped in fragments.
        if isinstance(component, (Foreach, Cond)):
            component = Fragment.create(component)

        component = _into_component_once(component)

        if component is None:
            msg = "The render function must return a component."
            raise ValueError(msg)

        # Set the component key.
        if component.key is None:
            component.key = index

        return component

View on GitHub (pinned to 45b8ed5ab7)

Solutions

  1. Wrap returned values in a component: `rx.text(item.name)`
  2. Ensure every branch of the render function returns a component (use `rx.fragment()` as an empty fallback)

Example fix

# before
rx.foreach(State.items, lambda item: item.name)

# after
rx.foreach(State.items, lambda item: rx.text(item.name))
Defensive patterns

Strategy: type-guard

Validate before calling

import reflex as rx

def returns_component(fn, sample_item) -> bool:
    return isinstance(fn(sample_item), rx.Component)

Type guard

import reflex as rx

def is_component_returning_fn(fn) -> bool:
    import typing
    ret = typing.get_type_hints(fn).get("return", None)
    return isinstance(ret, type) and issubclass(ret, rx.Component)

Prevention

When it happens

Trigger: `rx.foreach(State.items, lambda item: item.name)` (returns a str instead of `rx.text(item.name)`), or a render fn with a branch returning None.

Common situations: Assuming foreach auto-wraps values like `rx.text` does, or early-return logic inside the render function that forgets a component on one path.

Related errors


AI-assisted analysis of reflex-dev/reflex@45b8ed5ab7 (2026-08-28). Data as JSON: /api/errors/9ce4346cef2a7c35. Report an issue: GitHub.