Dynamic
Renders a component function or an element chosen by a tag name, and re-renders when component changes.
Renders a component function or an element chosen by a tag name, and re-renders when
component changes. Only component is tracked: the rest of the props are passed through
reactive, so changing them updates the rendered output without rebuilding it. Swapping
component disposes the old subtree, cleanups included, and builds the new one once. A falsy
component renders nothing.
Tag names are checked against ^[a-z][a-z0-9-]*$ (case-insensitive) and script is refused, so
data-driven tags cannot inject markup. SVG-only names (circle, path, svg, ...) are created
in the SVG namespace.
Import#
import { Dynamic } from "@shadow-js/web";
Signature#
function Dynamic<C extends DynamicTarget>(props: DynamicProps<C>): () => unknown
Parameters#
| Name | Description |
|---|---|
props |
component and the props of what it renders. |
Returns#
An accessor of the rendered output, to be inserted by the caller.
Throws#
- TypeError for an invalid tag name or a component that is neither a string nor a function (at read time, which is when the caller inserts it).
Examples#
import { createRoot, useSignal } from "@shadow-js/core";
import { Dynamic, insert } from "@shadow-js/web";
const parent = document.createElement("div");
createRoot(() => {
const [level] = useSignal(1);
insert(
parent,
Dynamic({
get component() {
return level() === 1 ? "h1" : "h2";
},
children: "Title",
}),
);
});