Skip to content

Components and JSX

A component is a function that returns JSX and runs once. Each binding in the JSX updates one DOM attribute, property, or text node when the signal it reads changes, so the component itself does not run again. This page covers how components execute, how props and children behave, which JSX forms the compiler accepts, and how to choose a component at runtime.

The Counter component below increments count by props.step, offers a reset button, and shows a message once count reaches 10 or more:

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

export function Counter(props: { step: number }) {
  let count = signal(0);
  return (
    <section>
      <output>{count}</output>
      <button onClick={() => (count += props.step)}>+{props.step}</button>
      <button onClick={() => (count = 0)} disabled={count === 0}>
        reset
      </button>
      <Show when={count >= 10}>
        <p>That is a lot of clicks.</p>
      </Show>
    </section>
  );
}

Each use of Counter creates one instance, and that instance runs once. Reading count or props.step inside the JSX creates a binding, and assigning count updates only the bindings that read it.

Component execution

The runtime calls a component once and does not track the reads in its body, so the body never re-runs. Reads inside JSX create bindings, and reads inside event handlers run when the handler runs. In the following example, Link runs once. Clicking either button updates an attribute of the same anchor:

import { signal } from "reze-js";

function Link(props: { href: string; label?: string; title?: string }) {
  return (
    <a href={props.href} title={props.title}>
      {props.label ?? "home"}
    </a>
  );
}

export function Nav() {
  let href = signal("/a");
  let title = signal("t1");
  return (
    <>
      <button onClick={() => (href = "/b")}>Go to b</button>
      <button onClick={() => (title = "t2")}>Retitle</button>
      <Link href={href} title={title} />
    </>
  );
}

The compiler passes href={href} as a getter, so props.href reads the current value each time its binding runs. A signal copied into a variable at the top of the component body is different. The copy is read once and never updates, and the compiler reports it with SIGNAL_READ_ONCE:

import { signal } from "reze-js";

export function Counter() {
  let count = signal(0);
  const doubled = count * 2;
  return <button onClick={() => (count += 1)}>{doubled}</button>;
}

Read the signal where the value is used, or declare a derived value. For more information about derived values, see Reactivity.

Props

Props arrive as one object. A prop whose expression reads a signal is passed as a getter, so the component sees its current value wherever it reads the prop inside JSX.

Destructured props

A component can destructure its only parameter. The compiler rewrites each name into a read of the props object at the place the name is used, so the names stay reactive. It reports PROPS_REWRITTEN at information level for each rewritten component, and the sample below lists that code. A default applies while the prop is undefined, and a rest element holds the remaining props:

import { signal } from "reze-js";

function Link({ href, label = "home", ...rest }: { href: string; label?: string; title?: string }) {
  return (
    <a href={href} {...rest}>
      {label}
    </a>
  );
}

export function Nav() {
  let title = signal("t1");
  return (
    <>
      <button onClick={() => (title = "t2")}>Retitle</button>
      <Link href="/a" title={title} />
    </>
  );
}

The compiler does not rewrite every pattern. A default that calls a function is one of the refused forms. Each name in a refused pattern is read once, and it never updates. The compiler reports it with PROPS_DESTRUCTURED, and the message names the reason. Other refused forms include computed keys, nested defaults, nested rest elements, array patterns, and reassigned names:

export function Greeting({ name = fallback() }) {
  return <p>Hello {name}</p>;
}

To avoid the refused form, take props as the parameter and read props.name where the value is used.

Props helpers

mergeProps, splitProps, and omitProps combine and divide props. They are compiler syntax: a call with object literals and static keys becomes an object literal or an array of literals, and other calls compile to a runtime call. Call them directly; the compiler rejects a use as a value.

The following example uses each helper:

import { mergeProps, omitProps, signal, splitProps } from "reze-js";

function Button(props: { label?: string; kind?: string }) {
  const merged = mergeProps({ label: "Save", kind: "primary" }, props) as {
    label: string;
    kind: string;
  };
  return <button class={merged.kind}>{merged.label}</button>;
}

function Field(props: { label?: string; kind: string; hint: string }) {
  const [own, rest] = splitProps(props, ["label"]);
  return (
    <label title={rest.hint}>
      {own.label}
      <input />
    </label>
  );
}

function Plain(props: { label?: string; kind: string }) {
  const rest = omitProps(props, "kind") as { label?: string };
  return <button>{rest.label}</button>;
}

export function Demo() {
  let label = signal<string | undefined>(undefined);
  return (
    <>
      <button onClick={() => (label = "Send")}>Send</button>
      <button onClick={() => (label = undefined)}>Reset</button>
      <Button label={label} kind="ghost" />
      <Field label={label} kind="ghost" hint="Email" />
      <Plain label={label} kind="ghost" />
    </>
  );
}

mergeProps gives each key the value of the last source that is not undefined. In Button, the caller's kind wins over the default primary, and clicking Reset shows Save again. The getters stay reactive. splitProps returns one view for each key group, plus one view for the keys left over. omitProps returns a view without the listed keys. The result of mergeProps and omitProps is typed as Props, a record of unknown values, so the example asserts a narrower type. The result of splitProps is typed from its input.

Using one of them as a value, without calling it, is an error reported as PROPS_AS_VALUE:

import { omitProps } from "reze-js";

export const view = omitProps;

Refs on components

A ref on a component is not an ordinary prop. The component receives it as props.ref, and the component decides which element receives it. Forward the ref to an element, and the variable is assigned when that element mounts:

function Field(props: { ref?: HTMLInputElement | ((el: HTMLInputElement) => void) }) {
  return <input ref={props.ref} />;
}

export function Demo() {
  let input!: HTMLInputElement;
  return (
    <>
      <Field ref={input} />
      <button onClick={() => input.focus()}>Focus</button>
    </>
  );
}

A component that does not read props.ref leaves the variable unassigned. For refs on elements, see Building interfaces.

Children

Content between a component's tags arrives as props.children. The compiler passes it lazily, so a binding inside the children updates in place without rebuilding the component. The element nodes stay the same. In the following example, clicking the button changes the text to count 2 and keeps the <b> element:

import { signal, type JSX } from "reze-js";

function Card(props: { children?: JSX.Element }) {
  return <section>{props.children}</section>;
}

export function Demo() {
  let n = signal(1);
  return (
    <>
      <button onClick={() => (n += 1)}>Add one</button>
      <Card>
        count {n}
        <b />
      </Card>
    </>
  );
}

Supported JSX

The compiler accepts elements, fragments, expressions as children, and attributes. A value that reads a signal becomes a binding. Elements, fragments, and text compose in document order.

Attribute values

An attribute takes a plain value, not a function. The attribute types in the JSX namespace accept no function, so functions belong in children, in event handlers, and in ref callbacks. The following component updates the class and title attributes when the button changes online:

import { signal } from "reze-js";

export function Status() {
  let online = signal(true);
  return (
    <>
      <button onClick={() => (online = !online)}>Toggle</button>
      <p class={online ? "on" : "off"} title={online ? "online" : "offline"}>
        status
      </p>
    </>
  );
}

Fragments and spreads

A fragment (<> and </>) groups siblings without adding a DOM node. A spread on a native element, such as {...attrs}, applies each key to the element, and it re-applies when the values it reads change. An attribute written after the spread wins over the spread. A key that disappears from the spread is removed from the element. A spread on a component merges into the component's props, as Props helpers describes.

Dynamic components

dynamic takes a source function and returns a component. That component renders whichever component the source returns, and it re-evaluates the source when the signals it reads change. In the following example, the button assigns the component Italic to picked, and the next button assigns false:

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

function Bold(props: { label: string }) {
  return <b>{props.label}</b>;
}

function Italic(props: { label: string }) {
  return <i>{props.label}</i>;
}

export function Picker() {
  let picked = signal<typeof Bold | false>(Bold);
  let label = signal("a");
  const Picked = dynamic(() => picked);
  return (
    <>
      <button onClick={() => (picked = Italic)}>Italic</button>
      <button onClick={() => (picked = false)}>Hide</button>
      <button onClick={() => (label = "b")}>Relabel</button>
      <p>
        <Picked label={label} />
      </p>
    </>
  );
}

A new source result disposes the nodes of the previous component and builds the new one. When the source returns the same component again, nothing is rebuilt, and the props stay live. Changing label rewrites the text of the current component in place. A falsy result, such as false, renders nothing.

Assign the component itself to the signal, as picked = Italic does. Each call to dynamic returns a new component, so call it once per instance: at module scope, or in a component body, which runs once. Keep the call out of JSX and bindings.

Tag names chosen at runtime

A string literal returned by the source is a tag name. The compiler turns it into an element in the matching namespace, so dynamic(() => (round ? "circle" : "button")) renders an SVG circle or an HTML button. A string that is not a literal at the call site throws when the source returns it, and development builds name dynamicElement in the message. Use dynamicElement for tag names that come from runtime values:

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

export function Heading() {
  let level = signal("h2");
  const Title = dynamicElement(() => level);
  return (
    <>
      <button onClick={() => (level = "h3")}>Smaller</button>
      <Title class="title">Results</Title>
    </>
  );
}

dynamicElement renders the tag with the props and children it receives. A name of an SVG element gets the SVG namespace, math gets the MathML namespace, and other names get the HTML namespace. A falsy source result renders nothing.

Control-flow tags

Show, For, Repeat, Switch, Match, and Portal are compiler intrinsics. Each tag compiles to direct runtime calls, so the imported function only throws if it is called. Use these names only as JSX tags. Building interfaces covers what each tag is used for.

Each tag accepts a fixed set of attributes:

  • Show takes when, which is required, and fallback.
  • For takes each, which is required, fallback, and keyed. Its child is one row function.
  • Repeat takes count, which is required, and fallback. Its child is one row function.
  • Switch takes fallback. Its children must be Match elements.
  • Match takes when, which is required, and must be a direct child of Switch.
  • Portal takes mount.

Spreads and other attributes on these tags have no meaning, and the compiler reports them with CONTROL_FLOW_ATTRIBUTE:

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

export function Panel() {
  let open = signal(true);
  return (
    <>
      <button onClick={() => (open = false)}>Close</button>
      <Show when={open} keyed>
        <p>open</p>
      </Show>
    </>
  );
}

Using a control-flow name as a value is an error, reported as CONTROL_FLOW_AS_VALUE:

import { Show } from "reze-js";

export const Conditional = Show;

The following pages cover related topics:

  • Building interfaces: events, conditions, lists, styling, forms, element refs, portals, and async components.
  • Reactivity: signal, computed, store, and action.
  • Lifecycle: effect, ownership, cleanup, and context.
  • Familiar patterns: patterns from other frameworks and what to write instead.
  • Compiler: what the compiler lowers and its diagnostics.