Skip to content

createRef

createRef declares a ref at module scope: a name for one component in one interface. Bound to a <ui> it names the interface; bound to a static element it names the slot; bound anywhere else it is a ref like any other, and one that can be exported and handed to a component as a constant.

createRef(name?: string): Ref
src/marker.ts2
const plate = createRef('docs-marker:plate');
src/marker.ts2
<layer ref={plate} x="left" y="center" w={PLATE} h={PLATE}
  • name: A string. The durable name. On a <ui> it is the interface’s name; on a static element it is the slot’s. Optional — a ref that nothing outside the build addresses needs none.

A Ref, with every field useRef’s has. It is bound the same way, once, with ref={…}.

  • One name for one component. Bound twice, anywhere in the project, it is refused (TS2E214). For a component drawn several times — a mapped row — use useRef(), which is one handle per instance.
  • It travels as a constant. A useRef() handle cannot leave the render that made it; a createRef can be exported, imported, and handed to a component as an ordinary prop.
  • A <ui> with no ref has an id and no name, and nothing outside the build can open it.
refused/create-ref.ts2
const label = createRef("docs-refused-label");
const Refused = (): Component => (
<layer w="fill" h="fill">
<text ref={label} x={0} y={0} w="fill" h={16} text="one" font={Fonts.PLAIN} color={Colors.AMBER} />
<text ref={label} x={0} y={20} w="fill" h={16} text="two" font={Fonts.PLAIN} color={Colors.AMBER} />
</layer>
);
src/shop.ts2
const shopRef = createRef('docs-shop');
export const shopUi = (): UI => (
<ui ref={shopRef} w={252} h={260}>
src/integrating.ts2
export const walletSlot = createRef('docs-integrating:wallet');
src/integrating.ts2
<layer static ref={walletSlot} x={12} y={44} w={88} h={126}>
src/marker.ts2
<MoveButton label="Left" mode={0} x={0} target={plate} readout={readout} />

MoveButton declares target: Ref and writes through it.

src/watch.ts2
const poisonLabel = createRef('docs-watch:poison');
src/watch.ts2
useWatch(Varps.POISON, (event) => { writePoison(event.component); }, poisonLabel);

See Watching and reacting.

useRef() inside a component that may be drawn several times; createRef when there is exactly one of the thing, or when the name has to be known outside the build.

My ref is already bound to another element

Section titled “My ref is already bound to another element”

A module-scope ref names one component. If two elements need handles, declare two refs.