Forms and inputs
Bind inputs, checkboxes and selects to signals, validate with computeds, and handle submit without reloading the page.
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.
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"56let name = Signal.make("")7let plan = Signal.make("free")8let agreed = Signal.make(false)9let submitted = Signal.make(None)1011let nameError = Computed.make(() =>12 String.trim(Signal.get(name)) == "" ? Some("Tell us your name.") : None13)14let canSubmit = Computed.make(() => Signal.get(nameError) == None && Signal.get(agreed))1516let reset = () => {17 Signal.set(name, "")18 Signal.set(plan, "free")19 Signal.set(agreed, false)20}2122let 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}2930@xote.component31let make = () =>32 <form onSubmit={submit}>33 <label>34 {"Name"}35 <input36 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 <input50 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) => message60 | None => Signal.get(nameError)->Option.getOr("Ready to sign up.")61 }}62 </p>63 </form>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("")23@xote.component4let 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("")23<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")34<input type_="checkbox" checked={agreed} onChange={e => Signal.set(agreed, e->target->checked)} />56<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.") : None3)45let 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) => message4 | 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
onChangefor text. On text inputs,changefires only when the field loses focus. UseonInputto 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
| Item | Import / entry | First stable | Changed in 7.2.0 | Needs the PPX |
|---|---|---|---|---|
value, checked, disabled, type_, event props on intrinsic elements | xote (JSX via XoteJSX) | 7.0.0 | — | No (thunks or signals work without it) |
Reading Signal.get inline in an attribute | xote | 7.1.0 | — | Yes (@xote.component) |
attrs escape hatch, attribute removal with None | xote | 7.1.0 | — | No |
ref prop, View.Ref, View.onMount (focus management) | xote | 7.2.0 (new) | — | No |
Signal.batch | xote | stable (all 7.x) | — | No |
Rules
- Xote writes
value,checkedanddisabledas 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 returnsnull; CSS[value="…"]selectors do not match a bound value. - A string-typed attribute prop (
value,class,name,placeholder,min,max,step,pattern, …) accepts: astring, aSignal.t<string>, a thunkunit => string, or aMaybeSignal.t<string>. A signal or thunk makes it a reactive leaf. - A boolean prop (
checked,disabled,required,readOnly,multiple,autofocus,hidden) acceptsbool,Signal.t<bool>,unit => boolorMaybeSignal.t<bool>.falseremoves the attribute (or clears the property). maxLength,minLength,rows,colsandtabIndexare typedintand are applied once. They MUST NOT be passed a signal or thunk; useattrs=[("maxlength", …)]for a reactive value.- 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. - Binding is one-way (signal → DOM). The handler MUST write the user's input back: text fields in
onInput, checkboxes, radios and selects inonChange. onChangeon a text<input>or<textarea>fires only when the field commits (blur, or Enter). UseonInputfor per-keystroke state.- An event handler is not a tracking scope. Inside it,
Signal.peekandSignal.getbehave identically (no subscription);Signal.peekSHOULD be used to make that explicit. - A
<form>MUST haveonSubmitthat callspreventDefaulton the event, or submitting navigates/reloads the page. Pressing Enter in a field submits the form. - 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.
- Resetting a form is setting its signals back. Wrap several writes in
Signal.batchso dependents (computeds, effects, reactive leaves) update once. - For a
<select>, Xote appliesvalueafter the select's children (options) are created, so the initial value selects the matching option. - Xote provides no helper to read
event.target.value; declare the bindings in API below (once, in a shared module). - 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 throughattrs.
API
| Name | Signature | Behaviour |
|---|---|---|
value prop | string | Signal.t<string> | unit => string | MaybeSignal.t<string> | Sets el.value; reactive when given a signal/thunk. |
checked prop | bool | Signal.t<bool> | unit => bool | MaybeSignal.t<bool> | Sets el.checked. |
disabled prop | same as checked | Sets el.disabled. |
type_ prop | string | Renders type (type is a ReScript keyword). |
for_ prop | string | Renders for on <label>. |
onInput, onChange, onSubmit, onFocus, onBlur, onKeyDown | Dom.event => unit | DOM event listeners. |
attrs | array<(string, 'a)> | Any other attribute; all entries share one type (see Styling guide). |
ref | View.Ref.t | Receives the element (7.2.0). |
View.Ref.make | unit => View.Ref.t | Creates a ref. |
View.Ref.peek | View.Ref.t => option<Dom.element> | Reads the element without tracking. |
View.onMount | (unit => unit) => unit | Runs after the component's DOM is in the document; never on the server. |
Signal.batch | (unit => 'a) => 'a | Defers 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.res2@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("")23@xote.component4let 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")34@xote.component5let 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")23@xote.component4let 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 => None6 | Some(_) => Some("Enter an age between 0 and 149.")7 | None => Signal.get(ageText) == "" ? None : Some("Enter a whole number.")8 }9)1011@xote.component12let make = () =>13 <label>14 {"Age"}15 <input16 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)45let 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))910let 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 ->ignore29 }30}3132@xote.component33let 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"23@xote.component4let 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
-
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} … />orvalue={Signal.get(name)}inside the attribute. Why: the component body runs once, untracked; only attribute expressions become reactive leaves. -
onChangeon 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 DOMchangeevent on text fields fires on commit. -
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. -
Missing
preventDefault. Wrong:<form onSubmit={_ => save()}>. Symptom: the page reloads (or navigates to the form'saction), losing state. Right:onSubmit={e => { preventDefault(e); save() }}. -
Passing a signal to an
intprop. Wrong:<textarea rows={rowCount} />withrowCount: Signal.t<int>. Symptom: compile error (intexpected); if forced withObj.magic, the attribute renders garbage. Right:attrs=[("rows", () => Int.toString(Signal.get(rowCount)))]. -
<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 aSignal.batch).
Edge cases
- Writing a different string into
valuewhile 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)fromonInputnever re-writes the DOM with the same string. <select multiple>: Xote has noselectedprop, andvalueselects 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
valueprop) is valid: read it in the submit handler through a ref orFormData. required,pattern,min,maxenable native constraint validation; the browser blockssubmitevents for invalid fields only when the form has nonovalidateattribute.
SSR and hydration
- On the server,
valuerenders as an attribute (<input value="Ada" />) andchecked/disabledas presence attributes; inputs therefore show their values in the HTML. <select value>and<textarea value>render as avalueattribute, 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>withattrs=[("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: intmeans anintprop 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.valueis"";disabled={!Signal.get(canSubmit)}togglesbutton.disabledas fields change.
Related
/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 andView.onMountfor focus./docs/guides/styling—attrstyping and attribute removal./docs/api/view—View.Ref,View.onMount.