[]previous and next page

insert

Reactive child insertion: keeps the content of a region in sync with value.

Reactive child insertion: keeps the content of a region in sync with value.

  • A function is an accessor, wrapped in a render effect; it re-runs when its dependencies change.
  • null, undefined, booleans render nothing. Strings and numbers become one Text node, reused when the region already holds one. A Node is inserted itself. A DocumentFragment inserts a snapshot of its children. Arrays are flattened, nested arrays included.
  • Content goes before anchorNode, or at the end when it is null or omitted.
  • Arrays are reconciled in place: nodes that remain are never removed and re-added.
  • initial lists nodes already in the DOM (from hydration or splitText) so nothing is recreated.
  • During hydrate(), a region that adopted server text is compared with its first commit: in development, different text warns HYDRATION_TEXT_MISMATCH (on the console and in devtools) and the region shows the value computed by the client.

Import#

ts
import { insert } from "@shadow-js/web";

Signature#

ts
function insert(
  parent: Node,
  value: unknown,
  anchorNode?: Node | null,
  initial?: unknown,
): unknown

Parameters#

Name Description
parent Node that holds the region.
value The value or an accessor returning it.
anchorNode Node the content goes before; null or omitted appends.
initial Nodes already in place for this region. Undefined adopts the server's nodes while hydrating and starts empty otherwise.

Returns#

The value as accepted (a fragment yields the array of its nodes).

Throws#

  • TypeError (production message SHADOW_INSERT_CYCLE) when an array contains itself, and (SHADOW_INSERT_DEPTH) when an accessor returns accessors more than 10,000 levels deep. When the value is reactive, the error is raised inside its render effect and goes to the owner's error handler, like any effect error.

Examples#

ts
import { useSignal } from "@shadow-js/core";
import { anchor, insert } from "@shadow-js/web";

const list = document.createElement("ul");
const end = anchor(list, null);
const [items] = useSignal(["a", "b"]);
insert(list, () => items().map((name) => document.createTextNode(name)), end);