Skip to content

Commit 9b8aab9

Browse files
authored
Allow ref to be passed to Component (#5284)
Override the default `ref`/`id` behavior when passing a `ref` prop directly. Allows better integration with third-party libraries that provide a ref which should be attached to some other component.
1 parent c926b2f commit 9b8aab9

File tree

2 files changed

+19
-3
lines changed

2 files changed

+19
-3
lines changed

reflex/components/component.py

Lines changed: 7 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -280,6 +280,9 @@ class Component(BaseComponent, ABC):
280280
# The id for the component.
281281
id: Any = pydantic.v1.Field(default_factory=lambda: None)
282282

283+
# The Var to pass as the ref to the component.
284+
ref: Var | None = pydantic.v1.Field(default_factory=lambda: None)
285+
283286
# The class name for the component.
284287
class_name: Any = pydantic.v1.Field(default_factory=lambda: None)
285288

@@ -709,9 +712,10 @@ def _render(self, props: dict[str, Any] | None = None) -> Tag:
709712
attr.removesuffix("_"): getattr(self, attr) for attr in self.get_props()
710713
}
711714

712-
# Add ref to element if `id` is not None.
713-
ref = self.get_ref()
714-
if ref is not None:
715+
# Add ref to element if `ref` is None and `id` is not None.
716+
if self.ref is not None:
717+
props["ref"] = self.ref
718+
elif (ref := self.get_ref()) is not None:
715719
props["ref"] = Var(_js_expr=ref)
716720
else:
717721
props = props.copy()

tests/units/components/test_component.py

Lines changed: 12 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -2335,3 +2335,15 @@ def test_special_props(component_kwargs, exp_custom_attrs, exp_style):
23352335
for prop in SpecialComponent.get_props():
23362336
if prop in component_kwargs:
23372337
assert getattr(component, prop)._var_value == component_kwargs[prop]
2338+
2339+
2340+
def test_ref():
2341+
"""Test that the ref prop is correctly added to the component."""
2342+
custom_ref = Var("custom_ref")
2343+
ref_component = rx.box(ref=custom_ref)
2344+
assert ref_component._render().props["ref"].equals(custom_ref)
2345+
2346+
id_component = rx.box(id="custom_id")
2347+
assert id_component._render().props["ref"].equals(Var("ref_custom_id"))
2348+
2349+
assert "ref" not in rx.box()._render().props

0 commit comments

Comments
 (0)