[]previous and next page

Refs and forwardRef

Refs and forwardRef in the React to ShadowJS guide.

For agentsUpdated

A DOM ref is a variable or a callback. Declare let el: HTMLInputElement | undefined and write ref={el}; the compiler assigns the element when it creates it. A callback runs once with the element, before the element is inserted in the document, so do work that needs a mounted element (focus, measuring) in onMount.

Because the body runs once, a plain let variable also replaces useRef for mutable values that do not drive the UI.

forwardRef is not needed. ref is an ordinary prop: it arrives as props.ref and you place it on an element.

A { current } object works as React's useRef object does. current is the element while it is mounted and null after its owner is disposed:

src/box.tsxtsx
import { onMount } from "@shadow-js/core";

export function Box() {
  const box = { current: null as HTMLDivElement | null };
  onMount(() => console.log(box.current?.tagName, box.current !== null));
  return <div ref={box}>box</div>;
}
Expected output
DIV true
src/refs.tsxtsx
import { onMount } from "@shadow-js/core";
import type { Ref } from "@shadow-js/web";

export function Field(props: { ref?: Ref<HTMLInputElement> }) {
  return <input ref={props.ref} aria-label="Name" />;
}

export function Form() {
  let input: HTMLInputElement | undefined;
  onMount(() => input?.focus());
  return <Field ref={input} />;
}