From aeca9832900c3534ce1c49191517d62098c0919c Mon Sep 17 00:00:00 2001 From: Masen Furer Date: Wed, 1 May 2024 17:03:40 -0700 Subject: [PATCH] Allow StatefulComponent to also be rendered via __str__ (#3211) This makes it easier to implement React "render functions" when wrapping components that require children to be a callable. --- reflex/compiler/compiler.py | 2 +- reflex/components/component.py | 10 ++++++++++ 2 files changed, 11 insertions(+), 1 deletion(-) diff --git a/reflex/compiler/compiler.py b/reflex/compiler/compiler.py index 89ac867f7..9000b54f9 100644 --- a/reflex/compiler/compiler.py +++ b/reflex/compiler/compiler.py @@ -174,7 +174,7 @@ def _compile_root_stylesheet(stylesheets: list[str]) -> str: return templates.STYLE.render(stylesheets=sheets) -def _compile_component(component: Component) -> str: +def _compile_component(component: Component | StatefulComponent) -> str: """Compile a single component. Args: diff --git a/reflex/components/component.py b/reflex/components/component.py index 0f387b1d5..3442d8cb8 100644 --- a/reflex/components/component.py +++ b/reflex/components/component.py @@ -2103,6 +2103,16 @@ class StatefulComponent(BaseComponent): """ return dict(Tag(name=self.tag)) + def __str__(self) -> str: + """Represent the component in React. + + Returns: + The code to render the component. + """ + from reflex.compiler.compiler import _compile_component + + return _compile_component(self) + @classmethod def compile_from(cls, component: BaseComponent) -> BaseComponent: """Walk through the component tree and memoize all stateful components.