Skip to content

Commit edca217

Browse files
committed
simplify ensure_input_elements_are_controlled
1 parent 24cc64b commit edca217

File tree

2 files changed

+11
-23
lines changed

2 files changed

+11
-23
lines changed

src/reactpy_django/forms/components.py

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -105,7 +105,7 @@ def on_submit_callback(new_data: dict[str, Any]):
105105
convert_html_props_to_reactjs,
106106
convert_textarea_children_to_prop,
107107
set_value_prop_on_select_element,
108-
ensure_input_elements_are_controlled(),
108+
ensure_input_elements_are_controlled,
109109
intercept_anchor_links,
110110
strict=False,
111111
),

src/reactpy_django/forms/transforms.py

Lines changed: 10 additions & 22 deletions
Original file line numberDiff line numberDiff line change
@@ -64,32 +64,20 @@ def set_value_prop_on_select_element(vdom_tree: VdomDict) -> VdomDict:
6464
return vdom_tree
6565

6666

67-
def ensure_input_elements_are_controlled(event_func: Callable | None = None) -> Callable:
67+
def ensure_input_elements_are_controlled(vdom_tree: VdomDict) -> VdomDict:
6868
"""Adds an onChange handler on form <input> elements, since ReactJS doesn't like uncontrolled inputs."""
69+
if not isinstance(vdom_tree, dict):
70+
return vdom_tree
6971

70-
def mutation(vdom_tree: VdomDict) -> VdomDict:
71-
"""Adds an onChange event handler to all input elements."""
72-
if not isinstance(vdom_tree, dict):
73-
return vdom_tree
74-
75-
vdom_tree.setdefault("eventHandlers", {})
76-
if vdom_tree["tagName"] in {"input", "textarea"}:
77-
if "onChange" in vdom_tree["eventHandlers"]:
78-
pass
79-
elif isinstance(event_func, EventHandler):
80-
vdom_tree["eventHandlers"]["onChange"] = event_func
81-
else:
82-
vdom_tree["eventHandlers"]["onChange"] = EventHandler(
83-
to_event_handler_function(event_func or _do_nothing_event)
84-
)
85-
86-
if "children" in vdom_tree:
87-
for child in vdom_tree["children"]:
88-
mutation(child)
72+
vdom_tree.setdefault("eventHandlers", {})
73+
if vdom_tree["tagName"] in {"input"} and "onChange" not in vdom_tree["eventHandlers"]:
74+
vdom_tree["eventHandlers"]["onChange"] = EventHandler(to_event_handler_function(_do_nothing_event))
8975

90-
return vdom_tree
76+
if "children" in vdom_tree:
77+
for child in vdom_tree["children"]:
78+
ensure_input_elements_are_controlled(child)
9179

92-
return mutation
80+
return vdom_tree
9381

9482

9583
def intercept_anchor_links(vdom_tree: VdomDict) -> VdomDict:

0 commit comments

Comments
 (0)