diff --git a/reflex/.templates/jinja/web/pages/component.js.jinja2 b/reflex/.templates/jinja/web/pages/component.js.jinja2
new file mode 100644
index 0000000000..1a08c64c6a
--- /dev/null
+++ b/reflex/.templates/jinja/web/pages/component.js.jinja2
@@ -0,0 +1,2 @@
+{% import 'web/pages/utils.js.jinja2' as utils %}
+{{utils.render(component.render())}}
\ No newline at end of file
diff --git a/reflex/compiler/compiler.py b/reflex/compiler/compiler.py
index 16df3c81ac..e39b76845a 100644
--- a/reflex/compiler/compiler.py
+++ b/reflex/compiler/compiler.py
@@ -164,6 +164,18 @@ def _compile_root_stylesheet(stylesheets: List[str]) -> str:
return templates.STYLE.render(stylesheets=sheets)
+def _compile_component(component: Component) -> str:
+ """Compile a single component.
+
+ Args:
+ component: The component to compile.
+
+ Returns:
+ The compiled component.
+ """
+ return templates.COMPONENT.render(component=component)
+
+
def _compile_components(components: Set[CustomComponent]) -> str:
"""Compile the components.
diff --git a/reflex/compiler/templates.py b/reflex/compiler/templates.py
index 5f1298522d..e7cb3ee0aa 100644
--- a/reflex/compiler/templates.py
+++ b/reflex/compiler/templates.py
@@ -69,6 +69,9 @@ def get_template(name: str) -> Template:
# Template for Tailwind config.
TAILWIND_CONFIG = get_template("web/tailwind.config.js.jinja2")
+# Template to render a component tag.
+COMPONENT = get_template("web/pages/component.js.jinja2")
+
# Code to render a single NextJS page.
PAGE = get_template("web/pages/index.js.jinja2")
diff --git a/reflex/components/component.py b/reflex/components/component.py
index 147c5a17d2..e682614a5d 100644
--- a/reflex/components/component.py
+++ b/reflex/components/component.py
@@ -317,7 +317,9 @@ def __str__(self) -> str:
Returns:
The code to render the component.
"""
- return format.json_dumps(self.render())
+ from reflex.compiler.compiler import _compile_component
+
+ return _compile_component(self)
def _render(self) -> Tag:
"""Define how to render the component in React.
diff --git a/tests/components/test_component.py b/tests/components/test_component.py
index b351aeba18..33249c3dac 100644
--- a/tests/components/test_component.py
+++ b/tests/components/test_component.py
@@ -534,3 +534,23 @@ def test_component_with_only_valid_children(fixture, request):
== f"The component `{component.__name__}` only allows the components: `Text` as children. "
f"Got `Box` instead."
)
+
+
+@pytest.mark.parametrize(
+ "component,rendered",
+ [
+ (rx.text("hi"), "\n {`hi`}\n"),
+ (
+ rx.box(rx.heading("test", size="md")),
+ "\n \n {`test`}\n\n",
+ ),
+ ],
+)
+def test_format_component(component, rendered):
+ """Test that a component is formatted correctly.
+
+ Args:
+ component: The component to format.
+ rendered: The expected rendered component.
+ """
+ assert str(component) == rendered