Skip to content

Forms and inputs

Bind inputs, checkboxes and selects to signals, validate with computeds, and handle submit without reloading the page.

docs/guides/forms.md
Raw Markdown

Forms in Xote are plain HTML elements wired to signals. Each field reads its value from a signal and writes back on input, so validation, disabled buttons and resets are just more signal reads.

SignupForm.res
1@get external target: Dom.event => Dom.element = "target"
2@get external value: Dom.element => string = "value"
3@get external checked: Dom.element => bool = "checked"
4@send external preventDefault: Dom.event => unit = "preventDefault"
5
6let name = Signal.make("")
7let plan = Signal.make("free")
8let agreed = Signal.make(false)
9let submitted = Signal.make(None)
10
11let nameError = Computed.make(() =>
12 String.trim(Signal.get(name)) == "" ? Some("Tell us your name.") : None
13)
14let canSubmit = Computed.make(() => Signal.get(nameError) == None && Signal.get(agreed))
15
16let reset = () => {
17 Signal.set(name, "")
18 Signal.set(plan, "free")
19 Signal.set(agreed, false)
20}
21
22let submit = (evt: Dom.event) => {
23 preventDefault(evt)
24 if Signal.peek(canSubmit) {
25 Signal.set(submitted, Some(Signal.peek(name) ++ " joined the " ++ Signal.peek(plan) ++ " plan."))
26 reset()
27 }
28}
29
30@xote.component
31let make = () =>
32 <form onSubmit={submit}>
33 <label>
34 {"Name"}
35 <input
36 value={name}
37 placeholder="Ada Lovelace"
38 onInput={e => Signal.set(name, e->target->value)}
39 />
40 </label>
41 <label>
42 {"Plan"}
43 <select value={plan} onChange={e => Signal.set(plan, e->target->value)}>
44 <option value="free"> {"Free"} </option>
45 <option value="team"> {"Team"} </option>
46 </select>
47 </label>
48 <label>
49 <input
50 type_="checkbox"
51 checked={agreed}
52 onChange={e => Signal.set(agreed, e->target->checked)}
53 />
54 {"I agree to the terms"}
55 </label>
56 <button type_="submit" disabled={!Signal.get(canSubmit)}> {"Sign up"} </button>
57 <p>
58 {switch Signal.get(submitted) {
59 | Some(message) => message
60 | None => Signal.get(nameError)->Option.getOr("Ready to sign up.")
61 }}
62 </p>
63 </form>

Tell us your name.

Read values from events

Event handlers receive a Dom.event. To get the field's current value, add a few small bindings once, near the top of the file (or in a shared module):

1@get external target: Dom.event => Dom.element = "target"
2@get external value: Dom.element => string = "value"
3@get external checked: Dom.element => bool = "checked"
4@send external preventDefault: Dom.event => unit = "preventDefault"

e->target->value then gives you the text of an input, select or textarea, and e->target->checked the state of a checkbox.

Bind a text input

Keep the text in a signal. Pass the signal as value, and write to it in onInput:

1let name = Signal.make("")
2
3@xote.component
4let make = () =>
5 <input value={name} onInput={e => Signal.set(name, e->target->value)} />

Passing the signal itself keeps the field in sync: when code calls Signal.set(name, ""), the input clears. Xote writes value and checked as DOM properties, so this works after the user has typed.

A <textarea> works the same way, with value and onInput:

1let bio = Signal.make("")
2
3<textarea rows={4} value={bio} onInput={e => Signal.set(bio, e->target->value)} />

Bind checkboxes and selects

A checkbox uses checked and onChange. A <select> uses value and onChange, and its value picks the matching <option>:

1let agreed = Signal.make(false)
2let plan = Signal.make("free")
3
4<input type_="checkbox" checked={agreed} onChange={e => Signal.set(agreed, e->target->checked)} />
5
6<select value={plan} onChange={e => Signal.set(plan, e->target->value)}>
7 <option value="free"> {"Free"} </option>
8 <option value="team"> {"Team"} </option>
9</select>

Note the prop is type_, because type is a ReScript keyword.

Validate with computeds

Validation is derived state, so it belongs in a computed. It re-runs only when the fields it reads change:

1let nameError = Computed.make(() =>
2 String.trim(Signal.get(name)) == "" ? Some("Tell us your name.") : None
3)
4
5let canSubmit = Computed.make(() => Signal.get(nameError) == None && Signal.get(agreed))

Show the message wherever you need it. Under @xote.component, a switch on a signal read in the markup updates on its own:

1<p class="field-error">
2 {switch Signal.get(nameError) {
3 | Some(message) => message
4 | None => ""
5 }}
6</p>

Disable the submit button

Read the computed inside the attribute. The annotation turns that attribute into its own reactive binding:

1<button type_="submit" disabled={!Signal.get(canSubmit)}> {"Sign up"} </button>

Handle submit

Put the handler on the <form> with onSubmit, and call preventDefault so the browser does not reload the page. This also makes the Enter key submit the form.

Inside the handler, read the fields with Signal.peek. A handler is not a reactive scope, so there is nothing to subscribe to:

1let submit = (evt: Dom.event) => {
2 preventDefault(evt)
3 if Signal.peek(canSubmit) {
4 save({name: Signal.peek(name), plan: Signal.peek(plan)})
5 reset()
6 }
7}

Reset the form

Because each field follows its signal, resetting is just setting the signals back. Wrap several writes in Signal.batch if you want them to land as one update:

1let reset = () =>
2 Signal.batch(() => {
3 Signal.set(name, "")
4 Signal.set(plan, "free")
5 Signal.set(agreed, false)
6 })

Common mistakes

  • Reading a signal once into value. value={Signal.get(name)} on a field works under @xote.component, but passing the signal itself (value={name}) is shorter and makes the binding obvious.
  • Forgetting preventDefault. Without it, submitting a <form> reloads the page.
  • Validating in an effect. Writing an error signal from an effect works, but a computed is simpler and never goes out of sync.
  • Using onChange for text. On text inputs, change fires only when the field loses focus. Use onInput to react to every keystroke.

Summary

A Xote form is plain HTML elements bound to signals: each field's value (or checked) prop reads a signal, and an event handler writes the new value back with Signal.set. Xote has no two-way binding, no form library and no event-value helper; you add four small external bindings once. Derived state (errors, "can submit") MUST be a computed, never a signal written from an effect. The one rule that matters most: bind value={signal} (or read it in the attribute) and write back in onInput; never copy the value into the component body.

Availability

ItemImport / entryFirst stableChanged in 7.2.0Needs the PPX
value, checked, disabled, type_, event props on intrinsic elementsxote (JSX via XoteJSX)7.0.0—No (thunks or signals work without it)
Reading Signal.get inline in an attributexote7.1.0—Yes (@xote.component)
attrs escape hatch, attribute removal with Nonexote7.1.0—No
ref prop, View.Ref, View.onMount (focus management)xote7.2.0 (new)—No
Signal.batchxotestable (all 7.x)—No

Rules

  1. Xote writes value, checked and disabled as DOM properties (el.value, el.checked, el.disabled), not attributes. Consequence: Signal.set(name, "") clears a field the user has already typed in; getAttribute("value") on a bound input returns null; CSS [value="…"] selectors do not match a bound value.
  2. A string-typed attribute prop (value, class, name, placeholder, min, max, step, pattern, …) accepts: a string, a Signal.t<string>, a thunk unit => string, or a MaybeSignal.t<string>. A signal or thunk makes it a reactive leaf.
  3. A boolean prop (checked, disabled, required, readOnly, multiple, autofocus, hidden) accepts bool, Signal.t<bool>, unit => bool or MaybeSignal.t<bool>. false removes the attribute (or clears the property).
  4. maxLength, minLength, rows, cols and tabIndex are typed int and are applied once. They MUST NOT be passed a signal or thunk; use attrs=[("maxlength", …)] for a reactive value.
  5. Under @xote.component, an attribute expression on an intrinsic element that reads a signal (value={Signal.get(name)}) becomes a reactive leaf. value={name} (passing the signal) is equivalent and preferred: it is explicit and does not depend on PPX detection.
  6. Binding is one-way (signal → DOM). The handler MUST write the user's input back: text fields in onInput, checkboxes, radios and selects in onChange.
  7. onChange on a text <input> or <textarea> fires only when the field commits (blur, or Enter). Use onInput for per-keystroke state.
  8. An event handler is not a tracking scope. Inside it, Signal.peek and Signal.get behave identically (no subscription); Signal.peek SHOULD be used to make that explicit.
  9. A <form> MUST have onSubmit that calls preventDefault on the event, or submitting navigates/reloads the page. Pressing Enter in a field submits the form.
  10. Validation and "can submit" flags MUST be computeds derived from field signals. A computed recomputes only when a field it read changes, and it is never out of sync.
  11. Resetting a form is setting its signals back. Wrap several writes in Signal.batch so dependents (computeds, effects, reactive leaves) update once.
  12. For a <select>, Xote applies value after the select's children (options) are created, so the initial value selects the matching option.
  13. Xote provides no helper to read event.target.value; declare the bindings in API below (once, in a shared module).
  14. Props that are not in the JSX props record (for example inputmode, enterkeyhint, aria-invalid, aria-describedby) are a compile error as props; pass them through attrs.

API

NameSignatureBehaviour
value propstring | Signal.t<string> | unit => string | MaybeSignal.t<string>Sets el.value; reactive when given a signal/thunk.
checked propbool | Signal.t<bool> | unit => bool | MaybeSignal.t<bool>Sets el.checked.
disabled propsame as checkedSets el.disabled.
type_ propstringRenders type (type is a ReScript keyword).
for_ propstringRenders for on <label>.
onInput, onChange, onSubmit, onFocus, onBlur, onKeyDownDom.event => unitDOM event listeners.
attrsarray<(string, 'a)>Any other attribute; all entries share one type (see Styling guide).
refView.Ref.tReceives the element (7.2.0).
View.Ref.makeunit => View.Ref.tCreates a ref.
View.Ref.peekView.Ref.t => option<Dom.element>Reads the element without tracking.
View.onMount(unit => unit) => unitRuns after the component's DOM is in the document; never on the server.
Signal.batch(unit => 'a) => 'aDefers notifications until the outermost batch ends.
Computed.make(unit => 'a, ~name: string=?, ~equals: ('a, 'a) => bool=?) => Signal.t<'a>Derived value.

Event bindings to declare (canonical set):

1// src/FormEvent.res
2@get external target: Dom.event => Dom.element = "target"
3@get external value: Dom.element => string = "value"
4@get external checked: Dom.element => bool = "checked"
5@send external preventDefault: Dom.event => unit = "preventDefault"

Patterns

Text field — Use when: any text, email, password, search or textarea input.

1let name = Signal.make("")
2
3@xote.component
4let make = () =>
5 <input value={name} onInput={e => Signal.set(name, e->target->value)} />

Checkbox, select — Use when: boolean or one-of-many choices.

1let agreed = Signal.make(false)
2let plan = Signal.make("free")
3
4@xote.component
5let make = () =>
6 <div>
7 <input type_="checkbox" checked={agreed} onChange={e => Signal.set(agreed, e->target->checked)} />
8 <select value={plan} onChange={e => Signal.set(plan, e->target->value)}>
9 <option value="free"> {"Free"} </option>
10 <option value="team"> {"Team"} </option>
11 </select>
12 </div>

Radio group — Use when: a small one-of-many choice shown inline. Each radio computes its own checked.

1let size = Signal.make("m")
2
3@xote.component
4let make = () =>
5 <fieldset>
6 <label>
7 <input type_="radio" name="size" value="s" checked={Signal.get(size) == "s"} onChange={_ => Signal.set(size, "s")} />
8 {"Small"}
9 </label>
10 <label>
11 <input type_="radio" name="size" value="m" checked={Signal.get(size) == "m"} onChange={_ => Signal.set(size, "m")} />
12 {"Medium"}
13 </label>
14 </fieldset>

Numeric field with validation — Use when: the value is a number. Keep the raw text as the source of truth and parse in a computed; writing a parsed-and-reformatted string back into value while the user types moves the caret.

1let ageText = Signal.make("")
2let age = Computed.make(() => Int.fromString(Signal.get(ageText)))
3let ageError = Computed.make(() =>
4 switch Signal.get(age) {
5 | Some(n) if n >= 0 && n < 150 => None
6 | Some(_) => Some("Enter an age between 0 and 149.")
7 | None => Signal.get(ageText) == "" ? None : Some("Enter a whole number.")
8 }
9)
10
11@xote.component
12let make = () =>
13 <label>
14 {"Age"}
15 <input
16 type_="number"
17 attrs=[("inputmode", "numeric")]
18 value={ageText}
19 onInput={e => Signal.set(ageText, e->target->value)}
20 />
21 <span class="field-error"> {Signal.get(ageError)->Option.getOr("")} </span>
22 </label>

Form with derived validity, async submit and reset — Use when: a complete form posts to a server.

1let email = Signal.make("")
2let submitting = Signal.make(false)
3let error: Signal.t<option<string>> = Signal.make(None)
4
5let emailError = Computed.make(() =>
6 Signal.get(email)->String.includes("@") ? None : Some("Enter an email address.")
7)
8let canSubmit = Computed.make(() => Signal.get(emailError) == None && !Signal.get(submitting))
9
10let submit = (evt: Dom.event) => {
11 preventDefault(evt)
12 if Signal.peek(canSubmit) {
13 Signal.set(submitting, true)
14 saveEmail(Signal.peek(email))
15 ->Promise.thenResolve(() =>
16 Signal.batch(() => {
17 Signal.set(submitting, false)
18 Signal.set(email, "")
19 })
20 )
21 ->Promise.catch(_ => {
22 Signal.batch(() => {
23 Signal.set(submitting, false)
24 Signal.set(error, Some("Could not save. Try again."))
25 })
26 Promise.resolve()
27 })
28 ->ignore
29 }
30}
31
32@xote.component
33let make = () =>
34 <form onSubmit=submit>
35 <input type_="email" value={email} onInput={e => Signal.set(email, e->target->value)} />
36 <button type_="submit" disabled={!Signal.get(canSubmit)}> {"Save"} </button>
37 <p role="alert"> {Signal.get(error)->Option.getOr("")} </p>
38 </form>

(saveEmail is any string => promise<unit>.)

Focus a field when it appears (7.2.0) — Use when: a dialog or search box opens.

1@send external focus: Dom.element => unit = "focus"
2
3@xote.component
4let make = () => {
5 let field = View.Ref.make()
6 View.onMount(() => View.Ref.peek(field)->Option.forEach(focus))
7 <input ref=field type_="search" placeholder="Search" />
8}

Anti-patterns

  1. Copying the value in the component body. Wrong: let current = Signal.get(name) then <input value={current} />. Symptom: Signal.set(name, "") (e.g. after submit) does not clear the field; the field shows the value from first render. Right: <input value={name} … /> or value={Signal.get(name)} inside the attribute. Why: the component body runs once, untracked; only attribute expressions become reactive leaves.

  2. onChange on a text input. Wrong: <input value={query} onChange={e => Signal.set(query, e->target->value)} />. Symptom: the signal (and everything derived from it) updates only when the field loses focus. Right: onInput. Why: the DOM change event on text fields fires on commit.

  3. Validation written from an effect. Wrong: Effect.run(() => { Signal.set(error, Signal.get(name) == "" ? Some("…") : None); None }). Symptom: an extra signal to keep in sync; error can be stale for one update; writes inside effects can cascade. Right: let error = Computed.make(() => Signal.get(name) == "" ? Some("…") : None). Why: derived state is a computed by definition.

  4. Missing preventDefault. Wrong: <form onSubmit={_ => save()}>. Symptom: the page reloads (or navigates to the form's action), losing state. Right: onSubmit={e => { preventDefault(e); save() }}.

  5. Passing a signal to an int prop. Wrong: <textarea rows={rowCount} /> with rowCount: Signal.t<int>. Symptom: compile error (int expected); if forced with Obj.magic, the attribute renders garbage. Right: attrs=[("rows", () => Int.toString(Signal.get(rowCount)))].

  6. <button type="reset">. Symptom: the browser resets the DOM fields but not the signals; the UI and state disagree, and the next signal change overwrites the field again. Right: a regular button whose handler sets the signals (in a Signal.batch).

Edge cases

  • Writing a different string into value while the field has focus moves the caret to the end (browser behaviour). Transform input on blur or submit, not on every keystroke.
  • Setting a signal to the value it already holds does not notify (strict equality), so Signal.set(name, e->target->value) from onInput never re-writes the DOM with the same string.
  • <select multiple>: Xote has no selected prop, and value selects only one option. Read the choices in the handler (selectedOptions, via your own binding) and set selection imperatively through a ref if needed.
  • Options rendered later (for example from a resource) do not re-apply the select's value; write the value signal again after the options change.
  • An uncontrolled field (no value prop) is valid: read it in the submit handler through a ref or FormData.
  • required, pattern, min, max enable native constraint validation; the browser blocks submit events for invalid fields only when the form has no novalidate attribute.

SSR and hydration

  • On the server, value renders as an attribute (<input value="Ada" />) and checked/disabled as presence attributes; inputs therefore show their values in the HTML.
  • <select value> and <textarea value> render as a value attribute, which browsers ignore: until hydration the select shows its first option and the textarea is empty. Hydration then writes the properties. If this flash matters, render the matching <option> with attrs=[("selected", "")] on the server or put the text inside the textarea.
  • Event handlers attach on hydration; input typed before hydration finishes is not written to signals. View.onMount (focus) runs only in the browser, after hydration.

Verify

  • Compile errors: "The field X does not belong to type XoteJSX.Elements.props" means the attribute is not a typed prop; move it into attrs. This has type: Signal.t<…> But it's expected to have type: int means an int prop got a signal.
  • Test with Zekr + jsdom (see the Testing guide):
1// SignupForm.res: <input type_="email" placeholder="Email" value={email} onInput=…/>
2test("typing updates the signal; setting the signal clears the field", () => {
3 let {container} = Dom.render("")
4 View.mount(<SignupForm />, container)
5 let input = Dom.Query.getByPlaceholder(container, "Email")
6 Dom.Event.typeText(input, "ada@example.com")
7 let typed = assertEqual(Signal.peek(SignupForm.email), "ada@example.com")
8 Signal.set(SignupForm.email, "")
9 combineResults([
10 typed,
11 assertNone(Dom.Query.queryByDisplayValue(container, "ada@example.com")),
12 ])
13}),
  • Observable: after Signal.set(field, "") the element's .value is ""; disabled={!Signal.get(canSubmit)} toggles button.disabled as fields change.
  • /docs/learn/rendering — attribute and event rules this page relies on.
  • /docs/learn/computeds — validation as derived state.
  • /docs/advanced/batching — grouping resets.
  • /docs/learn/lifecycle — refs and View.onMount for focus.
  • /docs/guides/styling — attrs typing and attribute removal.
  • /docs/api/view — View.Ref, View.onMount.