Skip to content

Commit 143ee94

Browse files
author
User
committed
Force form content remount when submitted data changes
Preact/React does not reliably restore <select multiple> selection state during in-place reconciliation of option children. Force a complete unmount/remount of the <form> element by using a volatile React key that increments each time submitted_data triggers a re-render. This ensures defaultValue is applied on mount and that the DOM select element starts fresh with the correct selection.
1 parent 37fe051 commit 143ee94

1 file changed

Lines changed: 3 additions & 0 deletions

File tree

src/reactpy_django/forms/components.py

Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -58,6 +58,7 @@ def _django_form(
5858
bottom_children_count = hooks.use_ref(len(bottom_children))
5959
submitted_data, set_submitted_data = hooks.use_state({} or None)
6060
rendered_form, set_rendered_form = hooks.use_state(cast("Union[str, None]", None))
61+
render_count, set_render_count = hooks.use_state(0)
6162

6263
# Initialize the form with the provided data
6364
validate_form_args(top_children, top_children_count, bottom_children, bottom_children_count, form)
@@ -93,6 +94,7 @@ async def render_form():
9394
await ensure_async(initialized_form.save)()
9495
set_submitted_data(None)
9596

97+
set_render_count(render_count + 1)
9698
set_rendered_form(
9799
await ensure_async(initialized_form.render)(form_template or config.REACTPY_DEFAULT_FORM_TEMPLATE)
98100
)
@@ -126,6 +128,7 @@ async def _on_change(_event):
126128

127129
form_props = {
128130
"id": f"reactpy-{uuid}",
131+
"key": f"reactpy-{uuid}-{render_count}",
129132
# Intercept the form submission to prevent the browser from navigating
130133
"onSubmit": event(lambda _: None, prevent_default=True),
131134
}

0 commit comments

Comments
 (0)