Przeglądaj źródła

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.
Masen Furer 6 dni temu
rodzic
commit
9b8aab98d3

+ 7 - 3
reflex/components/component.py

@@ -280,6 +280,9 @@ class Component(BaseComponent, ABC):
     # The id for the component.
     id: Any = pydantic.v1.Field(default_factory=lambda: None)
 
+    # The Var to pass as the ref to the component.
+    ref: Var | None = pydantic.v1.Field(default_factory=lambda: None)
+
     # The class name for the component.
     class_name: Any = pydantic.v1.Field(default_factory=lambda: None)
 
@@ -709,9 +712,10 @@ class Component(BaseComponent, ABC):
                 attr.removesuffix("_"): getattr(self, attr) for attr in self.get_props()
             }
 
-            # Add ref to element if `id` is not None.
-            ref = self.get_ref()
-            if ref is not None:
+            # Add ref to element if `ref` is None and `id` is not None.
+            if self.ref is not None:
+                props["ref"] = self.ref
+            elif (ref := self.get_ref()) is not None:
                 props["ref"] = Var(_js_expr=ref)
         else:
             props = props.copy()

+ 12 - 0
tests/units/components/test_component.py

@@ -2335,3 +2335,15 @@ def test_special_props(component_kwargs, exp_custom_attrs, exp_style):
     for prop in SpecialComponent.get_props():
         if prop in component_kwargs:
             assert getattr(component, prop)._var_value == component_kwargs[prop]
+
+
+def test_ref():
+    """Test that the ref prop is correctly added to the component."""
+    custom_ref = Var("custom_ref")
+    ref_component = rx.box(ref=custom_ref)
+    assert ref_component._render().props["ref"].equals(custom_ref)
+
+    id_component = rx.box(id="custom_id")
+    assert id_component._render().props["ref"].equals(Var("ref_custom_id"))
+
+    assert "ref" not in rx.box()._render().props