Skip to content

Building interfaces

This page covers the features that shape what a component renders and how it responds to input: events, conditional and list rendering, styling, form fields, element references, portals, async views, and islands. Each section gives the rule, an example, and the compiler checks that apply to it.

Events

Event attributes use camel-case names such as onClick and onInput. Each takes a handler function that receives the DOM event:

import { signal } from "reze-js";

export function Stepper(props: { step: number }) {
  let count = signal(0);
  return (
    <div onClick={() => (count += props.step)}>
      <button>add {props.step}</button>
      <output>{count}</output>
    </div>
  );
}

Inside a handler, currentTarget is the element that declares the handler, even when the event starts at a child. Calling stopPropagation() on the event stops it from reaching ancestors that handle the same event.

Delegated and direct events

Eleven event types are delegated. Reze installs one listener per type on the document and calls the handler on the element that declares it:

  • click
  • input
  • change
  • submit
  • keydown
  • keyup
  • pointerdown
  • pointerup
  • pointermove
  • focusin
  • focusout

Every other event attaches its listener directly to the element. For example, onDoubleClick listens for dblclick on the element itself. A disabled <button> does not run its delegated onClick. Spread props use the same name mapping.

A lowercase name such as onclick={save} compiles to a click listener, and the compiler reports EVENT_NAME_LOWERCASE as a warning. Rename the attribute to camel case to clear the warning.

export function Save() {
  const save = () => {};
  return <button onclick={save}>save</button>;
}

Pass data to a handler

A two-element array passes data to the handler without a closure:

import { signal } from "reze-js";

export function Choices() {
  let picked = signal(0);
  const pick = (id: number) => (picked = id);
  return (
    <p>
      <button onClick={[pick, 1]}>one</button>
      <button onClick={[pick, 2]}>two</button>
      <output>{picked}</output>
    </p>
  );
}

For a delegated event, [handler, data] calls handler(data, event). For a direct listener, [handler, options] passes options to addEventListener, so [save, { once: true }] runs once.

Listen to any event name

The on: prefix attaches a direct listener for the name after the colon, with no camel-case mapping: on:scroll={onScroll} listens for scroll, and on:custom={[onCustom, { once: true }]} listens for custom once.

Conditional rendering

Inline conditions

Use && or ?: in JSX for a single condition. The branch builds its nodes when the test becomes truthy and disposes them when the test becomes falsy. While the test stays truthy, the nodes stay in place and their bindings update.

import { signal } from "reze-js";

export function Panel() {
  let open = signal(true);
  let text = signal("details");
  return (
    <div>
      <button onClick={() => (open = !open)}>toggle</button>
      <button onClick={() => (text = text === "details" ? "more details" : "details")}>change text</button>
      {open && <p>{text}</p>}
    </div>
  );
}

Changing text updates the paragraph in place. Setting open to false removes the paragraph, and setting it back to true builds a new one. A ternary such as {ready ? <b>ready</b> : <i>waiting</i>} follows the same rule: a change between two values with the same truthiness keeps the nodes, and a flip rebuilds the active side.

Show and Switch

Show renders its children while when is truthy and fallback otherwise. Without a fallback, a falsy when renders nothing. A function child receives the tested value, which reads as a signal:

import { Show, signal } from "reze-js";

export function Greeting() {
  let name = signal("Ada");
  return (
    <div>
      <input value={name} onInput={(e: InputEvent) => (name = (e.currentTarget as HTMLInputElement).value)} />
      <Show when={name} fallback={<p>anonymous</p>}>
        {(value) => <p>hello {value}</p>}
      </Show>
    </div>
  );
}

Clearing the input makes name falsy, which shows the fallback.

Calling the value reads the getter itself instead of the value, so the compiler reports it with FLOW_PARAM_CALLED:

import { Show } from "reze-js";

export const view = <Show when="Ada">{(value) => <p>hello {value()}</p>}</Show>;

Switch renders the first Match whose when is truthy, or its fallback when none match. It rebuilds only when the chosen Match changes:

import { Match, Switch, signal } from "reze-js";

export function Status() {
  let code = signal(200);
  return (
    <div>
      <button onClick={() => (code = 404)}>not found</button>
      <Switch fallback={<p>unknown</p>}>
        <Match when={code === 200}>
          <p>ok</p>
        </Match>
        <Match when={code === 404}>
          <p>missing</p>
        </Match>
      </Switch>
    </div>
  );
}

A function child of Match receives its when, which reads as a signal as in Show. Match works only as a direct child of Switch, so use Show for a single condition:

import { Match } from "reze-js";

export function Ready(props: { ready: boolean }) {
  return (
    <div>
      <Match when={props.ready}>
        <b>ready</b>
      </Match>
    </div>
  );
}

Lists

Choose a row identity

For renders one row per item. Its keyed prop decides which rows are kept when each changes:

Modekeyed valueRows followRow item argumentRow index argument
IdentityOmitted, or keyed={true}The item objectThe item itselfThe position, read as a signal
Keyed functionkeyed={(item) => key}The key the function returnsThe item, read as a signalThe position, read as a signal
Positionkeyed={false}The array positionThe item, read as a signalThe position as a number

The following component renders todos with a function key. Removing a row removes that row's nodes:

import { For, signal } from "reze-js";

interface Todo {
  id: number;
  title: string;
}

export function Todos() {
  let todos = signal<Todo[]>([
    { id: 1, title: "write" },
    { id: 2, title: "review" },
  ]);
  return (
    <ul>
      <For each={todos} fallback={<li>empty</li>} keyed={(todo) => todo.id}>
        {(todo, index) => (
          <li>
            {index}: {todo.title} <button onClick={() => (todos = todos.filter((t) => t.id !== todo.id))}>remove</button>
          </li>
        )}
      </For>
    </ul>
  );
}

In keyed-function mode, replacing an item with another object that has the same key keeps the row's nodes and updates todo in place. Reordering moves the existing nodes. In identity mode, a new object builds a new row. The fallback renders when each is empty, null, undefined, or false.

Keep keys stable for the lifetime of a row. Use identity mode for stable objects, a keyed function when items are replaced but keep the same logical identity, and position mode when a row belongs to its array slot.

keyed is read once when the list is built, and it must be true, false, or a key function, so the compiler knows which row parameters read as signals. A value it cannot decide is an error reported as FOR_KEYED_DYNAMIC:

import { For } from "reze-js";

const numbers = [1, 2, 3];

export function Rows(props: { mode: boolean }) {
  return (
    <ul>
      <For each={numbers} keyed={props.mode}>
        {(n) => <li>{n}</li>}
      </For>
    </ul>
  );
}

An array literal passed directly to each builds new items on every evaluation, so no row can be reused. The compiler reports INLINE_EACH as a warning:

import { For } from "reze-js";

export function Digits() {
  return (
    <ul>
      <For each={[1, 2, 3]}>{(n) => <li>{n}</li>}</For>
    </ul>
  );
}

Hoist the array to a module constant, or hold it in a signal.

The compiler reports KEY_ON_ELEMENT as a warning when key is set on a native element, because <For> is the only place rows are keyed:

export function Row() {
  return <li key="a">a</li>;
}

Repeat a fixed count

Repeat renders count rows, each passed its position as a plain number:

import { Repeat, signal } from "reze-js";

export function Placeholders() {
  let count = signal(2);
  return (
    <div>
      <button onClick={() => (count += 1)}>add row</button>
      <ul>
        <Repeat count={count} fallback={<li>none</li>}>
          {(index) => <li>row {index}</li>}
        </Repeat>
      </ul>
    </div>
  );
}

A count that is not a positive number renders zero rows, and a fraction is truncated. Growing count appends rows, and shrinking it removes rows from the end. fallback renders while there are no rows.

Select one row of many

selector(source) returns isSelected(key), a function that tells whether key is the current value of source. Use it when many rows compare themselves with one selection. With the default Object.is comparison, each row subscribes to its own key, so a change re-runs only the rows whose answer flipped: the row that was selected and the row that is now selected. The source is a getter, so pass () => active, not the signal itself:

import { For, selector, signal } from "reze-js";

const tabs = ["home", "docs", "blog"];

export function Tabs() {
  let active = signal("home");
  const isActive = selector(() => active);
  return (
    <nav>
      <For each={tabs}>
        {(tab) => (
          <button class={{ on: isActive(tab) }} onClick={() => (active = tab)}>
            {tab}
          </button>
        )}
      </For>
    </nav>
  );
}

Outside a tracked context, isSelected(key) returns the current answer without subscribing. A custom equals(key, value) replaces Object.is. With a custom equals, every live key is checked on each change, so the cost grows with the number of rows.

Styling

class accepts a string, null, undefined, false, a toggle object, or an array. style accepts a string or an object. The following component toggles a class and sets a width from signals:

import { signal } from "reze-js";

export function Badge() {
  let active = signal(false);
  let width = signal(1);
  return (
    <div>
      <button onClick={() => (active = !active)}>toggle</button>
      <button onClick={() => (width += 1)}>wider</button>
      <p class={["btn", { active: active }]}>
        <b style={{ display: "block", width: width + "px" }}>bar</b>
      </p>
    </div>
  );
}

A string replaces the class attribute. null, undefined, and false remove it. An object adds every space-separated class of each truthy key, so { "bg-sky-400 text-white": selected } toggles both classes together. An array applies its items in order, with nesting allowed. When two object keys name the same class, the later key decides whether it is on.

Object and array values change only the classes that the previous write applied to the element. Classes that other code added stay in place.

A style string sets the element's cssText. A style object takes kebab-case CSS property names. Within the object, null and undefined remove that property. As the whole value, null or undefined removes the style attribute. In the example, width updates when width changes and display stays as written.

Three prefixes select lower-level writes:

  • bool:hidden={hidden} toggles the boolean hidden attribute.
  • attr:aria-label={label} writes an attribute. Namespaced names such as xlink:href also write attributes. null, undefined, and false remove the attribute.
  • prop:customThing={value} assigns a JavaScript property with that exact name.

Forms

Bind the current value to value and update the signal from the event that reports the edit:

import { signal } from "reze-js";

export function Draft() {
  let draft = signal("");
  let submitted = signal("");
  const submit = () => {
    const title = draft.trim();
    if (title === "") return;
    submitted = title;
    draft = "";
  };
  return (
    <div>
      <input
        value={draft}
        onInput={(e: InputEvent) => (draft = (e.currentTarget as HTMLInputElement).value)}
        placeholder="Something to do"
      />
      <button onClick={submit}>Add</button>
      <p>submitted: {submitted}</p>
    </div>
  );
}

On an HTML element, value, checked, selected, textContent, and innerHTML are written as DOM properties rather than attributes. On a <select>, value selects the matching <option> once the options are in place.

A checkbox bound to a store item follows the same pattern. The handler writes the item, and the bindings read it:

import { For, store } from "reze-js";

interface Todo {
  id: number;
  title: string;
  done: boolean;
}

export function TodoList() {
  const todos = store<Todo[]>([{ id: 1, title: "write", done: false }]);
  return (
    <ul>
      <For each={todos}>
        {(todo) => (
          <li class={{ done: todo.done }}>
            <label>
              <input type="checkbox" checked={todo.done} onChange={() => (todo.done = !todo.done)} />
              {todo.title}
            </label>
          </li>
        )}
      </For>
    </ul>
  );
}

The checkbox reflects done through checked, the row reflects it through class, and the change handler flips the item in place.

createUniqueId() returns an id that is unique on the page. Use it to connect a label to an input in a component that can render more than once:

import { createUniqueId } from "reze-js";

export function Field(props: { label: string }) {
  const id = createUniqueId();
  return (
    <div>
      <label for={id}>{props.label}</label>
      <input id={id} />
    </div>
  );
}

Each call returns a new id, so call it once per instance. In a client-only build, ids are r followed by a number from a module-level counter. In server-rendered output, an id created inside an island is i<island>-<n> on the server and in the browser, so the island keeps the id its markup was built with. Outside an island the id comes from the component's position in the render tree.

Element references

ref gives you the DOM element after the compiler builds it. Assign the reference to an identifier, to a member of an object, or to a callback:

export function Canvas() {
  let canvas!: HTMLDivElement;
  const refs: { bar?: HTMLElement } = {};
  const seen: Element[] = [];
  return (
    <div ref={canvas}>
      <b ref={refs.bar} />
      <i ref={(el: Element) => seen.push(el)} />
    </div>
  );
}

After mounting, canvas is the <div>, refs.bar is the <b>, and seen holds the <i>. A callback runs untracked, so reading signals inside it does not subscribe the caller. Read a reference after the element is mounted, such as in an event handler.

Portals

Portal keeps its children in a different parent. Without mount, or with mount={null}, the children go to the document body. Children stay reactive wherever they are mounted.

This component renders a <b> inside a separate <section> while open is truthy:

import { Portal, signal } from "reze-js";

export function Dialog() {
  let open = signal(true);
  let target!: HTMLElement;
  return (
    <div>
      <button onClick={() => (open = !open)}>toggle</button>
      <section ref={target} />
      {open && (
        <Portal mount={target}>
          <b>modal</b>
        </Portal>
      )}
    </div>
  );
}

When mount is reactive, the same nodes move to the new parent. Children stay reactive after a move, components inside stay alive, and a delegated event inside the portal still reaches its handler. Toggling a portal leaves nothing behind in the mount.

An error thrown while building portal children reaches the nearest catchError, the same as an error in inline content. For error handling in general, see Lifecycle.

Head tags

Head renders its children into the document head and leaves nothing inline. Children can be <title>, <base>, <meta>, <link>, <script> and <style> elements; anything else fails to compile:

import { Head, signal } from "reze-js";

export function Gallery() {
  let caption = signal("Photos");
  return (
    <section>
      <Head>
        <title>{caption}</title>
        <script src="https://cdn.example.test/gallery.js" async />
        <link rel="preconnect" href="https://cdn.example.test" />
        <meta property="og:title" content={caption} />
        <script type="application/ld+json">{'{"@type":"Gallery"}'}</script>
      </Head>
      <h1>{caption}</h1>
      <button onClick={() => (caption = "More photos")}>more</button>
    </section>
  );
}

Each tag has a key that names it in the head. <title> and <base> are their own keys, meta is keyed by exactly one of name, property and http-equiv, <link rel="canonical"> by its rel, any other link by rel plus href, and script by src. The attributes that form a key must be known at compile time, except the href of a canonical link: a string literal, or a const declared earlier in the same module whose value is a string literal or a template of such constants, such as const SDK = "https://cdn.example/sdk.js" read as <script src={SDK} />. Imported bindings are not resolved, so declare the constant in the module that renders the tag. A script without src needs a non-executable type such as application/ld+json. Spreads, event handlers and island attributes never run for a head tag, title, script and style take only text, and the other tags take no children. <noscript> is not supported, because a parser moves its children out of the head.

A keyed tag replaces the tag with the same key while its component is mounted: the tags of src/document.tsx come first, then each shell, layout and route component overrides them, and the deepest one wins. Disposing the component shows the replaced tag again. A script with the same src adopts the live tag, so it executes once even when two routes share it. Tags without a key, such as <style> or a JSON-LD <script>, add to the head and leave with their last owner.

The server applies the same rule to SSR and SSG pages, including tags from async components, which arrive with a later patch. See page metadata for routes.

Async components

An async function component awaits data in its body and renders a view when the awaits finish. Where it is used, wrap it in <Loading> to show a fallback during the first load and in <Errored> to show a rejected await:

import { abortSignal, Errored, isPending, Loading } from "reze-js";

async function Profile(props: { id: number }) {
  const id = props.id;
  const user = await fetch(`/users/${id}`, {
    signal: abortSignal(),
  }).then((r) => r.json());
  return <p class={isPending() ? "stale" : ""}>{user.name}</p>;
}

export function Page() {
  return (
    <Errored fallback={(error, reset) => <button onClick={reset}>{String(error)}</button>}>
      <Loading fallback={<i>loading</i>}>
        <Profile id={1} />
      </Loading>
    </Errored>
  );
}

Loading and Errored

<Loading fallback> renders fallback until every async component below it has settled its first load, then shows them all at once. During the first load, isPending() is false. A reload does not show fallback again. The view runs with isPending() set to true until the reload settles.

<Errored fallback> catches a rejected await, and an error thrown while building or in an effect, anywhere below it. fallback is an element, or a function (error, reset) => …. Calling reset builds the children again, so their loads run from the start. A try around an await is a compile error, so let the rejection reach <Errored>. Errors thrown in event handlers are not caught.

Both boundaries are compiled away like <Show>, and both belong at the use site: assigning pending or failure to a component is a compile error, ASYNC_VIEW_PROPERTY.

Abort and pending state

Call isPending() in the view. Call abortSignal() directly in the load, not in the view. A newer run of the load aborts the signal of the run it supersedes, and the current run's signal stays live. The fetch in the example uses it to cancel a stale request.

Nested boundaries

Each async component waits for the nearest <Loading> above it. An inner <Loading> reveals its part on its own, and the outer one does not wait for it.

Split code with dynamic import

await import() inside an async component loads a module when the component runs, and the nearest <Loading> shows its fallback until the import resolves. The three files below show a split chart:

export async function Chart(props: { values: number[] }) {
  const values = props.values;
  const { Plot } = await import("./Plot");
  return <Plot values={values} />;
}
export function Plot(props: { values: number[] }) {
  return <p>{props.values.join(", ")}</p>;
}
import { Loading } from "reze-js";

import { Chart } from "./Chart";

export function Report() {
  return (
    <Loading fallback={<p class="skeleton">loading</p>}>
      <Chart values={[1, 2, 3]} />
    </Loading>
  );
}

Rules for async components

The compiler checks the shape of an async component's body:

  • Read props into a const before the first await. A props read inside an awaited expression is a compile error, ASYNC_PROPS_READ_IN_AWAIT:
export async function Card(props: { id: number }) {
  const user = await fetchUser(props.id);
  return <p>{user.name}</p>;
}
  • Do not wrap an await in try. The compiler reports ASYNC_TRY_AROUND_AWAIT, and a rejection goes to the nearest <Errored>:
export async function Card(props: { id: number }) {
  const id = props.id;
  try {
    const user = await fetchUser(id);
    return <p>{user.name}</p>;
  } catch {
    return <p>Failed</p>;
  }
}
  • Call isPending() only in the view, and call abortSignal() only directly in the load. Other calls are compile errors, IS_PENDING_OUTSIDE_VIEW and ABORT_SIGNAL_OUTSIDE_LOAD.

Islands

An island is a component that the page renders before it loads. Reze renders the island's fallback first, then loads the component when its trigger fires. Islands use the same loading path as async components, so the fallback also renders while a promise from load is pending.

There are two ways to write one. The island() function takes the loader as an argument. The island attribute on a component tag is compiled to a call to island() for the client target, and its companion attributes become the arguments.

Call island

island(trigger, load, props, fallback?, options?) returns the island. Its arguments are:

  • trigger: an IslandTrigger, one of "eager", "idle", "visible", "media", or "interaction".
  • load: a function that returns the component, or a promise for it. It runs when the trigger fires, so import() inside it starts the download at that point. With "eager", it runs at once.
  • props: the props passed to the component.
  • fallback: an optional function that returns the placeholder, such as () => <p>loading</p>.
  • options: an optional IslandOptions object. media is the query for the "media" trigger, and rootMargin is the margin for the "visible" trigger.
TriggerLoads whenRenders before loading
eagerAt onceNothing, or fallback while a promise from load is pending
idleOn the first idle period, after 2000 ms at most (after 200 ms where requestIdleCallback is missing)fallback
visibleWhen the shell scrolls into view, with options.rootMargin around the viewport (default 200px)A <span data-island="visible"> holding fallback
mediaWhen the options.media query matches, at once if it already doesfallback
interactionOn the first pointerdown, focusin, or keydown inside the shellA <span data-island="interaction"> holding fallback

Without a fallback, the visible and interaction shell gets display:block;min-width:1px;min-height:1px so that it can be observed.

The examples below use a counter component, defined in its own module:

import { signal } from "reze-js";

export function Counter(props: { step: number }) {
  let count = signal(0);
  return <button onClick={() => (count += props.step)}>{count}</button>;
}

This example renders the counter when it scrolls near the viewport. load returns the component through a dynamic import, which starts only when the trigger fires:

import { island } from "reze-js";

export function Page() {
  return (
    <main>
      <h1>Dashboard</h1>
      {island<{ step: number }>(
        "visible",
        () => import("./Counter").then((m) => m.Counter),
        { step: 1 },
        () => (
          <p>loading counter</p>
        ),
        { rootMargin: "400px" },
      )}
    </main>
  );
}

A failed load renders the fallback of the nearest <Errored> around the island. See Async components.

Adopt the server DOM

When the compiler proves that an island's view is a static element tree with value bindings, the island claims the DOM the server rendered instead of building a second copy and replacing it. The nodes keep their identity: scroll positions inside the island, focus, form values, a playing video and CSS transitions survive the load, and there is no layout shift. Event handlers and bindings attach to the same nodes, so the island is interactive with the markup it already has.

The proof rejects any island whose view contains a component, a <Show>, <For>, <Repeat>, <Switch>, <Portal>, <Head>, an async component, a dynamic tag, or an innerHTML/textContent binding, and any island that receives rendered children. Such an island renders again and replaces its markup, exactly as before. The descriptor sent to the browser carries the decision, and the browser checks the claimed roots against the server nodes; a mismatch falls back to the replacing path, so a refused shape is never half-adopted.

Use the island attribute

On a component tag, island makes the component an island, and the companion attributes configure it:

  • island by itself, or island={true}, is "eager".
  • island="visible" sets the trigger. The value must be a string literal. A value read from a variable is reported as ISLAND_TRIGGER.
  • islandMedia="(max-width: 40rem)" is the media option, and island="media" requires it.
  • islandRootMargin="400px" is the rootMargin option.
  • islandFallback={<p>loading</p>} is the fallback, written as an element instead of a function.

This dashboard renders the counter with the attribute form and the same fallback:

import { Counter } from "./Counter";

export function Dashboard() {
  return (
    <main>
      <h1>Dashboard</h1>
      <Counter island="visible" islandRootMargin="400px" step={1} islandFallback={<p>loading counter</p>} />
    </main>
  );
}

Split island components

The attribute form moves the component's code into its own chunk when the import line names only that component, the importing file does not export that name, and every use is an island. The compiler then lowers the loader to a dynamic import() of that module. Otherwise it reports ISLAND_NOT_SPLIT and keeps the static import.

Render islands on the server

In server-rendered and statically generated output, an eager island renders its component into the HTML and the browser boots it at once. Every other trigger renders only its fallback, inside the <span data-island> shell for visible and interaction, and never renders the component. The server still calls load to learn which module the island boots from, and it sends the trigger and the islandMedia and islandRootMargin values with the island. The browser arms the trigger and loads the component when it fires.

When an island boots, it does not hydrate the server markup. It renders its component again and replaces the markup inside its range, reusing the data the server already loaded. Slot content stays in place. Form fields the user has edited keep their values, and the focused field keeps its focus and cursor. Other DOM state inside the island, such as scroll positions and references to the server elements, does not carry over.

For <Counter island="visible" islandFallback={<p>loading counter</p>} />, the HTML contains the data-island="visible" span with the paragraph inside, and no markup from Counter. To produce this output, see Server rendering and Static site generation.

The island attribute is optional in server-rendered output. The compiler already finds the components that need the browser, and only those load. The attribute chooses when a component loads, and it keeps a component out of the HTML.

Check island diagnostics

The compiler checks the attribute form. An unknown trigger, or a value that is not a literal, is ISLAND_TRIGGER:

import { Counter } from "./Counter";

export function Sometimes() {
  return <Counter island="sometimes" step={1} />;
}

The media trigger needs the query in islandMedia. Without it, the compiler reports ISLAND_MEDIA_MISSING:

import { Counter } from "./Counter";

export function Responsive() {
  return <Counter island="media" step={1} />;
}

island marks a component tag. On a native element it is reported as ISLAND_ON_ELEMENT:

export function Plain() {
  return <section island="visible">hi</section>;
}

islandMedia, islandRootMargin, and islandFallback need island on the same tag. Without it, the compiler reports ISLAND_ORPHAN:

import { Counter } from "./Counter";

export function Orphan() {
  return <Counter islandRootMargin="400px" step={1} />;
}

A component that is also used outside an island stays in the main chunk, and the compiler reports ISLAND_NOT_SPLIT:

import { Counter } from "./Counter";

export function Shared() {
  return (
    <main>
      <Counter island="visible" step={1} />
      <Counter step={2} />
    </main>
  );
}
  • Components for component execution, props, children, and dynamic.
  • Reactivity for signals, derived values, stores, and actions.
  • Lifecycle for ownership, effects, disposal, and error handling.
  • Vite plugin for building static output and the ssg option.