Skip to content

Components

Write components with JSX, pass them props and children, and mount your app.

docs/learn/components.md
moduleXote.Viewboundarysrc/View.resientryxote · xote/viewversion7.2.0
Raw MarkdownAPI reference

A component is a function that returns a piece of UI. You write it with JSX, give it props, and compose it with other components. It runs once; the signals it reads keep it up to date afterwards (see Thinking in signals).

Write a component

Put each component in a module with a make function, and mark it with @xote.component. Labeled arguments become its props.

1module Greeting = {
2 @xote.component
3 let make = (~name: string) => <h1> {"Hello, "} {name} </h1>
4}
5
6<Greeting name="Ada" />

A file is a module too, so Greeting.res with a top-level make is used as <Greeting /> from other files. ReScript allows one component per module: put the next one in its own file or submodule.

Optional props and children

Make a prop optional with =?; it arrives as an option. Accept nested content with a ~children prop.

1module Card = {
2 @xote.component
3 let make = (~title: string, ~subtitle: option<string>=?, ~children: View.node) =>
4 <section class="card">
5 <h2> {title} </h2>
6 {switch subtitle {
7 | Some(text) => <p class="card-subtitle"> {text} </p>
8 | None => View.null()
9 }}
10 <div class="card-body"> {children} </div>
11 </section>
12}
13
14<Card title="Settings" subtitle="Changes save automatically">
15 <p> {"Nothing to configure yet."} </p>
16</Card>

View.null() renders nothing.

Props that change

Props are read once, when the component runs. For a prop that should update, pass a signal and read it in the component's JSX:

1module Badge = {
2 @xote.component
3 let make = (~count: Signal.t<int>) => <span class="badge"> {Signal.get(count)} </span>
4}
5
6<Badge count=unreadCount />

When a prop can be either fixed or live, type it as MaybeSignal.t and read it with MaybeSignal.get. Callers wrap the value to say which it is:

1module Price = {
2 @xote.component
3 let make = (~amount: MaybeSignal.t<int>) => <span> {"quot;} {MaybeSignal.get(amount)} </span>
4}
5
6<Price amount={MaybeSignal.static(10)} />
7<Price amount={MaybeSignal.reactive(total)} />

Helpers that return markup

Not every piece of UI needs to be a component. In a file that uses @xote.component, a plain function that returns JSX gets the same treatment, signal reads included:

1let pill = (label: string, active: bool) =>
2 <span class={active ? "pill active" : "pill"}> {label} </span>
3
4@xote.component
5let make = () => <div> {pill("All", true)} {pill("Done", false)} </div>

Reach for a component when the piece has its own state or is reused across files; a helper is fine for small repeated bits.

Where state lives

  • Inside the component for state only it uses: create the signal in the component body. Each instance gets its own.
  • At module level for state shared across the app: a signal defined at the top of a file is one value everyone reads.
  • In Context for state shared by one part of the tree, like a form or a tab group, where each instance needs its own copy.

The Project structure guide goes further.

Mount your app

View.mountById renders a component into the element with that id. View.mount takes an element you already have.

1View.mountById(<App />, "app")

Keep the mount in its own entry file (say Main.res), since a module can't render itself by name.

Example: todo list

A small app built from three components. Each todo keeps its done state in its own signal, so ticking one updates that row and the counter, nothing else.

TodoList.res
1type todo = {id: int, text: string, done: Signal.t<bool>}
2
3let todos = Signal.make([...])
4let draft = Signal.make("")
5
6let remaining = Computed.make(() =>
7 Signal.get(todos)->Array.filter(todo => !Signal.get(todo.done))->Array.length
8)
9
10module TodoComposer = {
11 @xote.component
12 let make = () =>
13 <div>
14 <input
15 placeholder="Add a task"
16 value={Signal.get(draft)}
17 onInput={event => Signal.set(draft, target(event)["value"])}
18 />
19 <button onClick={_ => addTodo()}> {"Add"} </button>
20 </div>
21}
22
23module TodoRow = {
24 @xote.component
25 let make = (~todo: todo) =>
26 <li class={Signal.get(todo.done) ? "done" : ""}>
27 <input
28 type_="checkbox"
29 checked={Signal.get(todo.done)}
30 onChange={_ => Signal.update(todo.done, done => !done)}
31 />
32 <span> {todo.text} </span>
33 <button onClick={_ => removeTodo(todo.id)}> {"Remove"} </button>
34 </li>
35}
36
37@xote.component
38let make = () =>
39 <div>
40 <TodoComposer />
41 <p> {Signal.get(remaining)} {" left"} </p>
42 <ul>
43 <View.For
44 each={MaybeSignal.reactive(todos)}
45 by={todo => Int.toString(todo.id)}
46 render={todo => <TodoRow todo />}
47 />
48 </ul>
49 </div>
2 left
  • Learn ReScript
  • Learn signals
  • Write my first Xote component

Common mistakes

  • Reading a signal into a prop. <Badge count={Signal.get(count)} /> passes a snapshot. Pass count itself.
  • Reading a signal in the component body to show it. The body runs once, so the value never updates. Read it in the JSX.
  • Two components in one module. Use a submodule or a separate file for each.

Summary

A Xote component is a module whose make function returns a View.node; JSX <Name prop=... /> calls it. The component body runs exactly once per instance, untracked, and its result is mounted; afterwards only reactive leaves and reactive regions update. Props are ordinary function arguments read once: a prop that must change over time MUST be passed as a Signal.t, a MaybeSignal.t or a thunk, and read inside the child's JSX.

Availability

ItemModule / entryStable sinceChanged in 7.2.0PPX required
@xote.component annotationcompile-time PPX, "ppx-flags": ["xote/ppx/ppx"]7.1.0Reach into plain helper functions in the same file, condition-only tracking of if/switch, render-callback decompositionyes (it is the PPX)
@jsx.component with XoteJSXxote ("jsx": {"version": 4, "module": "XoteJSX"})7.1.0—no
View.mount, View.mountByIdxote · xote/view7.1.0—no
MaybeSignal (static, reactive, get, map, …)xote · xote/maybe-signal7.1.0 (replaces deprecated Prop)—no
Context for per-instance statexote · xote/context7.2.0 (new)—no

Configuration required in rescript.json for everything on this page: "jsx": {"version": 4, "module": "XoteJSX"}, "compiler-flags": ["-open Xote"] (or open Xote per file), and "ppx-flags": ["xote/ppx/ppx"] for @xote.component.

Rules

  1. A component MUST be a make function inside a module (a file is a module). Exactly one @xote.component or @jsx.component binding is allowed per module; a second one is a compile error: "Only one component definition is allowed for each module. Move to a submodule or other file if necessary."
  2. Labeled arguments of make become the props record. ~name: t is required; ~name: t=default is optional with a default; ~name: option<t>=? is optional and arrives as option<t> (the caller writes name=value, not name=Some(value)).
  3. ~children is an ordinary prop. Type it View.node when the component renders its children once. JSX with several children passes them as one fragment node.
  4. The component body (code before the returned JSX) runs once per instance, untracked: a Signal.get there is a read (untracked) and its value never updates. Since 7.1.0 the body is its own reactive scope (owner): signals, computeds, effects and resources created in it are owned by the instance and disposed when the instance is removed.
  5. The returned JSX is where reactivity is created. Under @xote.component, each attribute or bare child that reads a signal becomes a reactive leaf (see /docs/learn/rendering).
  6. Props of user components are NEVER made reactive by the PPX. <Child value={Signal.get(x)} /> evaluates Signal.get(x) once, where the element is written. To pass something that changes, pass x itself (typed Signal.t<'a>), a MaybeSignal.t<'a>, or a thunk unit => 'a, and read it in the child's JSX.
  7. Exception to rule 6: a prop whose value is JSX, or a function returning JSX (a render callback such as View.For's render), is decomposed like any other JSX in the file.
  8. The PPX opt-in is per file: in a file that contains at least one @xote.component, all JSX in the file is decomposed (7.2.0+ also reaches plain helper functions and JSX bound with let). A file with no @xote.component is left untouched, and bare {…} children of non-node type are then compile errors.
  9. Moving a helper that returns JSX between an annotated and a non-annotated file changes its behaviour (reactive vs one-shot) without a type change. Keep markup helpers in annotated files.
  10. View.mount(node, element) replaces the contents of element. View.mountById(node, id) does nothing when no element has that id. Neither hydrates; use Hydration.hydrate for server-rendered HTML.
  11. A module cannot refer to itself by name, so View.mountById(<App />, "app") MUST live in a different module than App (conventionally Main.res).
  12. A component instance has no identity across "re-renders" because components do not re-render. A component is created again only when the region that contains it is rebuilt (a branch swap, a keyed row replaced, View.tracked re-evaluated, an error boundary reset); then its body runs again and it gets fresh local state.

API

NameSignatureBehaviour
@xote.componentattribute on let makeDerives props like @jsx.component and decomposes the file's JSX into reactive leaves.
@jsx.componentattribute on let makeDerives props; no decomposition (reactivity only via thunks, signals, View.* primitives).
View.mount(node, Dom.element) => unitRenders node into the element, replacing its contents.
View.mountById(node, string) => unitmount by element id; no-op when the id is absent.
View.null / View.emptyunit => nodeRenders nothing (an empty text node that keeps the position).
View.fragmentarray<node> => nodeGroups nodes without a wrapper element.
MaybeSignal.static'a => MaybeSignal.t<'a>Wraps a constant; reading it subscribes nothing.
MaybeSignal.reactiveSignal.t<'a> => MaybeSignal.t<'a>Wraps a signal; MaybeSignal.get is a tracked read.
MaybeSignal.getMaybeSignal.t<'a> => 'aReads the value (tracked for Reactive). The PPX treats it as a signal read.
MaybeSignal.map(MaybeSignal.t<'a>, 'a => 'b) => MaybeSignal.t<'b>Maps a static or reactive value.

Patterns

Required, defaulted and optional props, typed children. Use when: any component with inputs.

1module Card = {
2 @xote.component
3 let make = (~title: string, ~subtitle: option<string>=?, ~children: View.node) =>
4 <section class="card">
5 <h2> {title} </h2>
6 {switch subtitle {
7 | Some(text) => <p> {text} </p>
8 | None => View.null()
9 }}
10 {children}
11 </section>
12}
13
14module Greeting = {
15 @xote.component
16 let make = (~name: string, ~greeting: string="Hello") => <h1> {greeting} {", "} {name} </h1>
17}
18
19<Card title="Totals" subtitle="Live"> <Greeting name="Ada" /> </Card>

A prop that changes: pass the signal. Use when: the child must follow a value owned elsewhere.

1module Badge = {
2 @xote.component
3 let make = (~count: Signal.t<int>) => <span class="badge"> {Signal.get(count)} </span>
4}
5
6let total = Signal.make(3)
7<Badge count=total />

A prop that may be fixed or live: MaybeSignal.t. Use when: one component serves both static and reactive callers.

1module Price = {
2 @xote.component
3 let make = (~amount: MaybeSignal.t<int>) => <span> {"quot;} {MaybeSignal.get(amount)} </span>
4}
5
6<Price amount={MaybeSignal.static(10)} />
7<Price amount={MaybeSignal.reactive(total)} />

A derived prop: pass a thunk. Use when: the child needs a value computed from several signals and you do not want a named Computed.

1module Label = {
2 @xote.component
3 let make = (~text: unit => string) => <span> {text()} </span>
4}
5
6<Label text={() => Signal.get(name)} />

Local state per instance. Use when: state belongs to one instance (each Counter has its own count).

1module Counter = {
2 @xote.component
3 let make = (~initial: int) => {
4 let count = Signal.make(initial)
5 <button onClick={_ => Signal.update(count, n => n + 1)}> {Signal.get(count)} </button>
6 }
7}

A markup helper (no annotation of its own) in an annotated file. Use when: small repeated markup without its own state.

1let pill = (label: string, active: bool) =>
2 <span class={active ? "pill active" : "pill"}> {label} </span>
3
4module Filters = {
5 @xote.component
6 let make = () => <div> {pill("All", true)} {pill("Done", Signal.get(total) > 0)} </div>
7}

Entry file. Use when: mounting the app (separate module from App).

1// Main.res
2View.mountById(<App />, "app")

State placement

State is…Put it inWhy
Used by one instance onlySignal.make in the component bodyOwned by the instance; disposed with it; each instance independent.
One value for the whole app (client-only)let x = Signal.make(...) at module levelSimplest; shared by every reader; never disposed.
Shared by one subtree, one copy per instance of an ancestor (tabs, form fields)Context providing a Signal.t (7.2.0)Scoped to the providing instance; see /docs/learn/context.
Per-request during SSRContext (7.2.0)Module-level signals are shared across requests in a server process.
Derived from other stateComputed.make next to its inputsNever store a copy that must be kept in sync.

Anti-patterns

Reading a signal in the body to display it.

1@xote.component
2let make = () => {
3 let label = Int.toString(Signal.get(count)) // read (untracked), once
4 <p> {label} </p>
5}

Symptom: the text shows the initial value and never changes. Fix: read in JSX, or bind a thunk.

1@xote.component
2let make = () => <p> {Signal.get(count)} </p>

Why: the body runs once, untracked; only expressions in JSX positions become reactive leaves.

Passing a snapshot as a prop.

1<Badge count={Signal.get(total)} />

Symptom: compile error when Badge expects Signal.t<int> (This has type: int … expected to have type: Xote.Signal.t<int>). If the prop is typed int, it compiles and the badge never updates. Fix: <Badge count=total /> with ~count: Signal.t<int>. Why: user-component props are evaluated once where written (rule 6). Inside an if/switch on a signal, such a read also subscribes the enclosing branch, so the branch is rebuilt wholesale whenever total changes.

Two components in one module.

1@xote.component
2let make = () => <div />
3@xote.component
4let make2 = () => <span />

Symptom: compile error "Only one component definition is allowed for each module." Fix: one component per module; use submodules (module Header = { @xote.component let make = ... }).

Mounting from the component's own module.

Symptom: View.mountById(<App />, "app") inside App.res fails to compile (a module cannot reference itself by name). Fix: put the mount in Main.res and point index.html at Main.res.mjs.

Helper with signal reads behind a cross-module call.

1<p class={Store.tone(store)}> {Store.count(store)} </p>

Symptom: renders once and never updates; in development, a one-time [Xote] … reads a signal through a call @xote.component cannot see warning. Fix: make the read visible or deferred: class={() => Store.tone(store)} and {() => Store.count(store)}. Why: signal detection is syntactic and does not follow other modules.

Edge cases

  • A component called as a function (View.mount(app(), container)) instead of through JSX runs its body before anything renders; its View.onMount (7.2.0) still waits for the mount. Prefer JSX (<App />).
  • ~children left untyped compiles ('children is inferred); type it View.node for clearer errors.
  • View.child (inserted by the PPX for bare children) accepts any value: a record or a variant compiles and renders [object Object] with a development warning. Convert to a string or node explicitly.
  • <View.Text>, <View.Int>, <View.Float>, <View.Bool> are detected by the PPX only when written qualified as View.X. open View + <Text> is not recognised; its child then fails to compile (string where View.node is expected).
  • The PPX's semantics are documented as "not settled yet" (ppx/README.md): the per-file opt-in may become an explicit file-level marker, View.child's accepted type may narrow, and one-shot prop reads may become explicitly untracked.

SSR and hydration

  • SSR.renderToString(() => <App />) runs every component body once on the server and serialises the result. Effects created in bodies run on the server too unless guarded with SSRContext.isClient; View.onMount (7.2.0) never runs on the server.
  • Hydration.hydrate(() => <App />, container) runs the bodies again on the client and attaches to the existing DOM instead of creating it. Bodies MUST produce the same structure on both sides (no random or time-based initial values in the first render).
  • Module-level signals in a server process are shared by all requests. Per-request state MUST be created in a body or provided through Context.

Verify

  • Compile: the errors quoted above identify rule violations (one component per module; prop type mismatch; bare non-node child in a non-annotated file).
  • Runtime (jsdom): mount, change a signal, assert the text changed and the component body ran once.
1let count = Signal.make(0)
2let bodyRuns = ref(0)
3
4module Probe = {
5 @xote.component
6 let make = () => {
7 bodyRuns := bodyRuns.contents + 1
8 <p id="out"> {Signal.get(count)} </p>
9 }
10}
11
12// In a test (jsdom): View.mountById(<Probe />, "app"); Signal.set(count, 2)
13// Expect: #out text == "2" and bodyRuns.contents == 1.
  • Observable: setting a signal updates only the bound text/attributes; DOM element identity of the component's root is unchanged.
  • /docs/learn/rendering — what in JSX becomes a reactive leaf, attributes, events, lists, conditionals.
  • /docs/learn/lifecycle — onMount, onCleanup, refs, portals, error boundaries (7.2.0).
  • /docs/learn/context — per-instance shared state.
  • /docs/thinking-in-signals — the run-once model.
  • /docs/api/view — full View reference.

API reference

This page lists the supported API for the View module.

Node is intentionally not expanded here. It currently exists as a compatibility alias, but new code and docs should use View.

View

View is the UI node API used by JSX components and lower-level rendering helpers.

View types

1type attrValue =
2 | Static(string)
3 | SignalValue(Signal.t<string>)
4 | Compute(unit => string)
5
6type node

View.node is the renderable value returned by components. View.attrValue is the supported attribute source type.

View.attr

1let attr: (string, string) => (string, View.attrValue)

Create a static attribute entry.

View.signalAttr

1let signalAttr: (string, Signal.t<string>) => (string, View.attrValue)

Create a reactive attribute from a string signal.

View.computedAttr

1let computedAttr: (string, unit => string) => (string, View.attrValue)

Create a reactive attribute from a compute function.

View.Attr

1View.Attr.string: (string, string) => (string, View.attrValue)
2View.Attr.signal: (string, Signal.t<string>) => (string, View.attrValue)
3View.Attr.compute: (string, unit => string) => (string, View.attrValue)

Namespaced aliases for View.attr, View.signalAttr, and View.computedAttr.

View.text

1let text: string => View.node

Create a static text node.

View.int

1let int: int => View.node

Create a static integer text node.

View.float

1let float: float => View.node

Create a static float text node.

View.bool

1let bool: bool => View.node

Create a static boolean text node.

View.signalText

1let signalText: (unit => string) => View.node

Create a reactive text node from a compute function.

View.signalInt

1let signalInt: (unit => int) => View.node

Create a reactive integer text node from a compute function.

View.signalFloat

1let signalFloat: (unit => float) => View.node

Create a reactive float text node from a compute function.

View.fragment

1let fragment: array<View.node> => View.node

Group several nodes without adding a wrapper element.

View.signalFragment

1let signalFragment: Signal.t<array<View.node>> => View.node

Render an array of nodes from a signal and replace the fragment when it changes.

View.tracked

1let tracked: (unit => View.node) => View.node

Create an auto-tracked reactive block. Every signal read while the body runs subscribes the block, and the body re-evaluates when any dependency changes. Dependencies are re-discovered on each run, so conditional reads work. The block's children are replaced wholesale (no diffing) on update — keep tracked blocks small and use View.For or View.eachWithKey for lists.

View.each

1let each: (Signal.t<array<'a>>, 'a => View.node) => View.node

Render each item from a reactive array. Updates re-render the list contents.

View.list

1let list: (Signal.t<array<'a>>, 'a => View.node) => View.node

Alias for View.each.

View.eachWithKey

1let eachWithKey: (Signal.t<array<'a>>, 'a => string, 'a => View.node) => View.node

Render a reactive array with keyed DOM reconciliation.

View.keyedList

1let keyedList: (Signal.t<array<'a>>, 'a => string, 'a => View.node) => View.node

Alias for View.eachWithKey.

View.For

1module For: {
2 type props<'item> = {
3 each: MaybeSignal.t<array<'item>>,
4 by?: 'item => string,
5 render: 'item => View.node,
6 }
7
8 let make: props<'item> => View.node
9}

JSX list primitive. Pass by to enable keyed reconciliation.

View.KeyedFor

1module KeyedFor: {
2 type props<'item> = {
3 each: MaybeSignal.t<array<'item>>,
4 by: 'item => string,
5 render: 'item => View.node,
6 }
7
8 let make: props<'item> => View.node
9}

JSX list primitive that always requires a key function.

View.Show

1module Show: {
2 type props = {
3 when_: MaybeSignal.t<bool>,
4 children?: View.node,
5 fallback?: View.node,
6 }
7
8 let make: props => View.node
9}

JSX conditional primitive for boolean branches.

View.Maybe

1module Maybe: {
2 type props<'value> = {
3 value: MaybeSignal.t<option<'value>>,
4 render: 'value => View.node,
5 fallback?: View.node,
6 }
7
8 let make: props<'value> => View.node
9}

JSX conditional primitive for option values.

View.Value

1module Value: {
2 type props<'value> = {
3 value: MaybeSignal.t<'value>,
4 render: 'value => View.node,
5 }
6
7 let make: props<'value> => View.node
8}

JSX primitive that re-renders a node from one static or reactive value.

View.Suspense

New in 7.2
1module Suspense: {
2 type props = {
3 fallback?: View.node,
4 children?: View.node,
5 }
6
7 let make: props => View.node
8}

Shows fallback until every Resource created below it has loaded once. The children render hidden meanwhile, and their refs and onMount callbacks wait until they are shown. See Resources.

View.Ref

New in 7.2
1module Ref: {
2 type t = View.elementRef
3
4 let make: unit => t
5 let fromCallback: (Dom.element => unit) => t
6 let get: t => option<Dom.element>
7 let peek: t => option<Dom.element>
8}

A handle on the DOM element a tag renders to. Pass it as ref (<input ref=field />, or ~ref on View.element). The element is handed over once it is in the document, before any onMount runs, and the ref reads None again once the element is removed. get is a tracked read; fromCallback also calls a function with each element.

View.onMount

New in 7.2
1let onMount: (unit => unit) => unit

Runs a callback once the calling component's DOM is in the document. Call it in a component body. It runs untracked, under the component's context and error boundary, and never during server rendering.

View.onCleanup

New in 7.2
1let onCleanup: (unit => unit) => unit

Runs a callback when the calling component is removed. Call it in a component body or inside its onMount.

View.Portal

New in 7.2
1module Portal: {
2 type props = {
3 target?: Dom.element,
4 children?: View.node,
5 }
6
7 let make: props => View.node
8}

Renders its children into target (document.body if omitted), and nothing where it stands; they are in the target before any onMount of the render runs. The children keep the portal's context and error boundary, and are removed with it.

View.ErrorBoundary

New in 7.2
1module ErrorBoundary: {
2 type props = {
3 fallback: (exn, unit => unit) => View.node,
4 onError?: exn => unit,
5 children?: View.node,
6 }
7
8 let make: props => View.node
9}

Catches what its subtree throws while rendering or updating and renders fallback instead. fallback receives the failure and a reset function that renders the subtree again; onError is called with every failure caught.

View.element

1let element: (
2 string,
3 ~attrs: array<(string, View.attrValue)>=?,
4 ~events: array<(string, Dom.event => unit)>=?,
5 ~children: array<View.node>=?,
6 ~ref: View.elementRef=?,
7 unit,
8) => View.node

Create an element node for any tag.

View.null

1let null: unit => View.node

Create an empty placeholder text node.

View.empty

1let empty: unit => View.node

Alias for View.null.

View.mount

1let mount: (View.node, Dom.element) => unit

Render a node into a DOM element.

View.mountById

1let mountById: (View.node, string) => unit

Look up a DOM element by id and mount into it.

View.Text

1<View.Text>{value}</View.Text>
2<View.Text value={value} />

JSX text primitive. value or children may be a raw string, Signal.t<string>, MaybeSignal.t<string>, or unit => string.

View.Int

1<View.Int>{value}</View.Int>
2<View.Int value={value} />

JSX integer text primitive. value or children may be a raw int, Signal.t<int>, MaybeSignal.t<int>, or unit => int.

View.Float

1<View.Float>{value}</View.Float>
2<View.Float value={value} />

JSX float text primitive. value or children may be a raw float, Signal.t<float>, MaybeSignal.t<float>, or unit => float.

View.Bool

1<View.Bool>{value}</View.Bool>
2<View.Bool value={value} />

JSX boolean text primitive. value or children may be a raw bool, Signal.t<bool>, MaybeSignal.t<bool>, or unit => bool.

Example

1open Xote
2
3let count = Signal.make(0)
4
5let app = () => {
6 <div>
7 <View.Text> "Count: " </View.Text>
8 <View.Int> {count} </View.Int>
9 <button onClick={_ => Signal.update(count, n => n + 1)}>
10 <View.Text> "Increment" </View.Text>
11 </button>
12 </div>
13}
14
15View.mountById(app(), "app")

See Also