Form
Forms are used to collect user input. The rx.form component is used to group inputs and submit them together.
The form component's children can be form controls such as rx.input, rx.checkbox, rx.slider, rx.text_area, rx.radio_group, rx.select or rx.switch. The controls should have a name attribute that is used to identify the control in the form data. The on_submit event trigger submits the form data as a dictionary to the handle_submit event handler.
The form is submitted when the user clicks the submit button or presses enter on the form controls.
Results
{}
type='submit'.Fields with the Same Name
Several controls can share a name, such as a group of checkboxes. A dict
annotation keeps only the last value submitted for each name. To receive every
value in the order the form submitted them, annotate the handler's parameter
with rx.form.FormData and read them with getlist (or its alias getAll, as in
the browser's FormData):
class ToppingsState(rx.State):
toppings: list[str] = []
@rx.event
def handle_submit(self, form_data: rx.form.FormData[str, str]):
self.toppings = form_data.getlist("topping")
def toppings_form():
return rx.form(
rx.el.input(type="checkbox", name="topping", value="cheese"),
rx.el.input(type="checkbox", name="topping", value="olives"),
rx.button("Submit", type="submit"),
on_submit=ToppingsState.handle_submit,
)rx.form.FormData is a read-only mapping: indexing it with
form_data["topping"] returns the last value, the same as a dict, and
form_data.multi_items() returns every (name, value) pair. A
TypedDict can also collect repeated
names with a list[str] field.
Validating Form Data with a TypedDict
The on_submit handler usually receives the form data as a plain dict, which
means accessing a field is untyped (form_data["email"] returns Any) and a
typo in a name goes unnoticed until runtime.
Instead, you can annotate the handler's parameter with a
TypedDict.
This gives you typed, autocompleted access to each field inside the handler, and
Reflex validates the form at compile time: every required key of the
TypedDict must have a matching form control. If a required field has no
control with that name (or id), Reflex raises an EventHandlerValueError
before the app starts, pointing out exactly which fields are missing.
Results
null
Required and optional fields
By default every key declared in a TypedDict is required and must be
backed by a form control. Mark a field as optional with NotRequired (or by
inheriting from a total=False base) so Reflex won't require a matching
control:
from typing import TypedDict
from typing_extensions import NotRequired
class ContactForm(TypedDict):
name: str # required: a control named "name" must exist
email: str # required: a control named "email" must exist
message: NotRequired[str] # optional: no control requiredList and bool fields
Two kinds of TypedDict fields are filled in even when the form submits no
value for them:
- A
list[str]field holds every value submitted under its name, in order, or an empty list when there are none. - A
boolfield isFalsewhen no value was submitted under its name, so an unchecked checkbox or switch reads asFalseinstead of a missing key. A submitted value isTrueunless, ignoring case and surrounding whitespace, it is empty or"false","off","no","n"or"0", so a select, radio group or hidden input submitting"false"reads asFalse.
When no value is submitted for a field whose type allows None, such as
list[str] | None or bool | None, the field is None instead. A field
marked NotRequired is left out when no value is submitted for it, whatever
its type.
class PreferencesForm(TypedDict):
toppings: list[str] # every checked "toppings" checkbox
subscribe: bool # False when the checkbox is unchecked
notify: bool | None # None when the switch is off
class PreferencesState(rx.State):
preferences: PreferencesForm | None = None
@rx.event
def handle_submit(self, form_data: PreferencesForm):
self.preferences = form_data
def preferences_form():
return rx.form(
rx.el.input(type="checkbox", name="toppings", value="cheese"),
rx.el.input(type="checkbox", name="toppings", value="olives"),
rx.checkbox("Subscribe", name="subscribe"),
rx.switch(name="notify"),
rx.button("Submit", type="submit"),
on_submit=PreferencesState.handle_submit,
)ExpandCollapse
Other fields keep the last value submitted for their name.
Generic TypedDicts work too, such as class Data(Base[list[str]]). On
Python 3.11, a further typing.TypedDict subclass of Data loses those type
arguments and Reflex rejects the form when it compiles, so define these
TypedDicts with typing_extensions.TypedDict instead.
If a required field is missing, creating the form fails fast with a message that lists the expected, missing, and matching fields:
class SignupForm(TypedDict):
username: str
email: str
class SignupState(rx.State):
@rx.event
def handle_submit(self, form_data: SignupForm): ...
# Raises EventHandlerValueError: the form has no control named "email".
rx.form(
rx.input(name="username"),
rx.button("Submit", type="submit"),
on_submit=SignupState.handle_submit,
)Dynamic Forms
Forms can be dynamically created by iterating through state vars using rx.foreach.
This example allows the user to add new fields to the form prior to submit, and all
fields will be included in the form data passed to the handle_submit function.
Results
{}
API Reference
rx.form
The Form component.
Props
| Prop | Type | Description |
|---|---|---|
access_key | str | Provides a hint for generating a keyboard shortcut for the current element. |
auto_capitalize | "off""none""on""sentences""words""characters" | Controls whether and how text input is automatically capitalized as it is entered/edited by the user. |
content_editable | "inherit""plaintext-only" | Indicates whether the element's content is editable. |
context_menu | str | Defines the ID of a <menu> element which will serve as the element's context menu. |
dir | str | Defines the text direction. Allowed values are ltr (Left-To-Right) or rtl (Right-To-Left). |
draggable | bool | Defines whether the element can be dragged. |
enter_key_hint | "enter""done""go""next""previous""search""send" | Hints what media types the media element is able to play. |
hidden | bool | Defines whether the element is hidden. |
input_mode | "none""text""tel""url""email""numeric""decimal""search" | Defines the type of the element. |
item_prop | str | Defines the name of the element for metadata purposes. |
lang | str | Defines the language used in the element. |
role | "alert""alertdialog""application""article""banner""button""cell""checkbox""columnheader""combobox""complementary""contentinfo""definition""dialog""directory""document""feed""figure""form""grid""gridcell""group""heading""img""link""list""listbox""listitem""log""main""marquee""math""menu""menubar""menuitem""menuitemcheckbox""menuitemradio""navigation""none""note""option""presentation""progressbar""radio""radiogroup""region""row""rowgroup""rowheader""scrollbar""search""searchbox""separator""slider""spinbutton""status""switch""tab""table""tablist""tabpanel""term""textbox""timer""toolbar""tooltip""tree""treegrid""treeitem" | Defines the role of the element. |
slot | str | Assigns a slot in a shadow DOM shadow tree to an element. |
spell_check | bool | Defines whether the element may be checked for spelling errors. |
tab_index | int | Defines the position of the current element in the tabbing order. |
title | str | Defines a tooltip for the element. |
as_child | bool | Change the default rendered element for the one passed as a child. |
accept | str | MIME types the server accepts for file upload. |
accept_charset | str | Character encodings to be used for form submission. |
action | str | URL where the form's data should be submitted. |
auto_complete | str | Whether the form should have autocomplete enabled. |
enc_type | str | Encoding type for the form data when submitted. |
method | str | HTTP method to use for form submission. |
name | str | Name of the form. |
no_validate | bool | Indicates that the form should not be validated on submit. |
target | str | Where to display the response after submitting the form. |
reset_on_submit | bool | If true, the form will be cleared after submit. |
handle_submit_unique_name | str | The name used to make this form's submit handler function unique. |