Expose and component refs
Sometimes a parent needs a child to act now, rather than when a prop changes: focus the search field, reset a counter, scroll a list to its end. A component lists what a parent may call with defineExpose, and the parent holds the component with a template ref, as it would hold an element (Template refs), and calls what it exposes from client code.
Exposing functions
defineExpose takes an object of the component's local functions, each in shorthand:
import { defineExpose, useTemplateRef } from "@uxfront/unframework";
export default function SearchField({ label }: { label: string }) {
const input = useTemplateRef<HTMLInputElement>();
function focus() {
input.value?.focus();
}
defineExpose({ focus });
return (
<label class="search">
{label}
<input ref={input} type="search" />
</label>
);
}
import { useTemplateRef } from "@uxfront/unframework";
import SearchField from "./SearchField.uf.tsx";
export default function Header() {
const search = useTemplateRef<{ focus(): void }>();
return (
<header class="header">
<SearchField ref={search} label="Find" />
<button type="button" onClick={() => search.value?.focus()}>
Search
</button>
</header>
);
}
The parent declares the ref with an object type of what it calls, useTemplateRef<{ focus(): void }>(), attaches it with ref={search}, and calls it in a handler, search.value?.focus(). The ref is null until the child is mounted, so the call reads it with ?.:
import { cx } from "./_unframework/cx";
import { type ComponentPropsWithoutRef, type Ref, useImperativeHandle, useRef } from "react";
export interface SearchFieldHandle {
focus(): void;
}
export type SearchFieldAttributes = Omit<
ComponentPropsWithoutRef<"label">,
"label" | "children"
> & { ref?: Ref<SearchFieldHandle> };
export default function SearchField({
label,
className,
style,
ref,
...attributes
}: { label: string } & SearchFieldAttributes) {
const input = useRef<HTMLInputElement>(null);
function focus() {
input.current?.focus();
}
useImperativeHandle(ref, () => ({ focus }));
return (
<label className={cx("search", className)} style={style} {...attributes}>
{label}
<input ref={input} type="search" />
</label>
);
}
import SearchField from "./SearchField";
import { cx } from "./_unframework/cx";
import { type ComponentPropsWithRef, useRef } from "react";
export type HeaderAttributes = Omit<ComponentPropsWithRef<"header">, "children">;
export default function Header({ className, style, ...attributes }: HeaderAttributes) {
const search = useRef<{ focus(): void }>(null);
return (
<header className={cx("header", className)} style={style} {...attributes}>
<SearchField ref={search} label="Find" />
<button type="button" onClick={() => search.current?.focus()}>
Search
</button>
</header>
);
}
- React passes the ref as a prop,
ref, which the child fills withuseImperativeHandle. The child exports the handle's type,SearchFieldHandle, and the parent readssearch.current. - Vue writes
defineExpose, and the parentuseTemplateRef("search")withref="search". - Svelte exports each function from the component,
export function focus(), and the parent binds aletwithbind:this. - Angular makes each exposed function a public method, and the rest protected where the template reads them, private otherwise. The parent writes a template reference,
#search, and reads it withviewChild. - Solid passes a
refcallback, which the child calls with what it exposes, and the parent empties itsletwithonCleanup. - Qwik has no component instance to hold, so the parent passes a signal as
ref, and the child fills it with its$functions and empties it when it is removed, through an inline helper,exposeRef(expose, emulated). - Astro renders on the server only, so nothing calls what a component exposes: the ref and its calls are dropped (
expose, for information).
The argument is an object literal of local functions, by name: no state, no computed value and no function written in place (UF2030). Expose a function that reads or writes the state instead. A ref whose type names a function the component doesn't expose is UF3046. A ref on a component that exposes nothing holds its root element (below).
Several functions
A component may expose several functions, declared with function or as an arrow function:
import { defineExpose, ref } from "@uxfront/unframework";
export default function Counter({ start }: { start: number }) {
const count = ref(start);
function increment() {
count.value++;
}
const reset = () => {
count.value = start;
};
defineExpose({ increment, reset });
return <output class="count">{count.value}</output>;
}
The parent's ref type lists the ones it calls, useTemplateRef<{ increment(): void; reset(): void }>(), and each button calls one.
Call what a child exposes from client code only, as you'd read an element ref: a handler, a watcher's callback or a lifecycle hook (Template refs).
A ref on a component that exposes nothing
A ref on a component that doesn't call defineExpose holds its root element, as Vue's $el does. It reaches through a chain of root components, and it holds the root whatever inheritAttrs says (Fallthrough). Type it as that element's DOM interface, by its name:
import { onMounted, ref, useTemplateRef } from "@uxfront/unframework";
// Exposes nothing, so a ref on it holds its root element. Its own template ref on that element
// still holds it once mounted, beside the parent's: `onMounted` reads it, and its focus listener
// fills the field only if it did.
export default function NameField({ label }: { label: string }) {
const input = useTemplateRef<HTMLInputElement>();
const mounted = ref(false);
onMounted(() => {
mounted.value = input.value !== null;
});
function fill() {
if (input.value && !input.value.value && mounted.value) input.value.value = "Ada";
}
return <input ref={input} name="name" aria-label={label} onFocus={fill} />;
}
import { defineOptions } from "@uxfront/unframework";
// Turns fallthrough off and spreads no rest: a ref on it still holds its root element.
export default function Bio({ label }: { label: string }) {
defineOptions({ inheritAttrs: false });
return <input name="bio" aria-label={label} />;
}
import { useTemplateRef } from "@uxfront/unframework";
import Bio from "./Bio.uf.tsx";
import NameField from "./NameField.uf.tsx";
export default function Profile() {
const name = useTemplateRef<HTMLInputElement>();
const bio = useTemplateRef<HTMLInputElement>();
return (
<form aria-label="Profile">
<NameField ref={name} label="Name" />
<button type="button" onClick={() => name.value?.focus()}>
Edit name
</button>
<Bio ref={bio} label="Bio" />
<button type="button" onClick={() => bio.value?.focus()}>
Edit bio
</button>
</form>
);
}
NameField's root is an <input>, so the parent's ref is useTemplateRef<HTMLInputElement>(), and "Edit name" focuses it. The component's own template ref on the same element still holds it beside the parent's: onMounted reads it, and the focus listener fills the field only if it did. A ref of another type, or on a component whose root isn't one element, is UF3046.
import { mergeRefs } from "./_unframework/mergeRefs";
import {
type ComponentPropsWithRef,
useEffect,
useEffectEvent,
useMemo,
useRef,
useState,
} from "react";
export type NameFieldAttributes = Omit<ComponentPropsWithRef<"input">, "label" | "children">;
export default function NameField({
label,
className,
style,
onFocus,
ref,
...attributes
}: { label: string } & NameFieldAttributes) {
const input = useRef<HTMLInputElement>(null);
const [mounted, setMounted] = useState(false);
const mountedRef = useRef(mounted);
const onMount = useEffectEvent(() => {
mountedRef.current = input.current !== null;
setMounted(mountedRef.current);
});
useEffect(() => {
onMount();
}, []);
function fill() {
if (input.current && !input.current.value && mountedRef.current) input.current.value = "Ada";
}
const rootRef = useMemo(() => mergeRefs(input, ref), [input, ref]);
return (
<input
ref={rootRef}
name="name"
aria-label={label}
onFocus={(event) => {
fill();
onFocus?.(event);
}}
className={className}
style={style}
{...attributes}
/>
);
}
import type { Ref, RefCallback } from "react";
/** Joins an element's refs into one ref callback, whose cleanup clears each. */
export function mergeRefs<E extends Element>(...refs: (Ref<E> | undefined)[]): RefCallback<E> {
return (element) => {
const cleanups = refs.map((ref) => {
if (typeof ref === "function") {
const cleanup = ref(element);
return typeof cleanup === "function" ? cleanup : () => ref(null);
}
if (ref) ref.current = element;
return () => {
if (ref) ref.current = null;
};
});
return () => {
for (const cleanup of cleanups) cleanup();
};
};
}
import Bio from "./Bio";
import NameField from "./NameField";
import { type ComponentPropsWithRef, useRef } from "react";
export type ProfileAttributes = Omit<ComponentPropsWithRef<"form">, "children">;
export default function Profile({ className, style, ...attributes }: ProfileAttributes) {
const name = useRef<HTMLInputElement>(null);
const bio = useRef<HTMLInputElement>(null);
return (
<form aria-label="Profile" className={className} style={style} {...attributes}>
<NameField ref={name} label="Name" />
<button type="button" onClick={() => name.current?.focus()}>
Edit name
</button>
<Bio ref={bio} label="Bio" />
<button type="button" onClick={() => bio.current?.focus()}>
Edit bio
</button>
</form>
);
}
- React passes the ref as React 19's
refprop, which reaches the root element. Where the root has a ref of its own, a shared helper,mergeRefs, joins the two into one ref callback, made once per pair withuseMemo. The parent's ref isuseRef<HTMLInputElement>(null). - Vue holds the child's instance,
useTemplateRef<{ $el: HTMLInputElement }>("nameComponent"), and the parent's ref is acomputedof its$el, the root element. - Svelte gives the child a
$bindablerefprop,ref?: HTMLElementTagNameMap["input"] | null, which its root binds beside its own ref through a function binding. The parent binds it to a$stateref,bind:ref={name}. - Angular's host is no element a ref may hold, so the child declares
ufElement, aviewChildof its root,ElementRef<HTMLInputElement>. The parent reads the child withviewChild("name", { read: NameField }), and its ref is acomputedof thatufElement(expose, emulated). - Solid passes a
refcallback, which the child's spread hands the root element, beside the root's ownrefcallback. - Qwik passes a signal as Qwik's own element ref, which the root fills beside its own ref,
if (ref) ref.value = element. - Astro renders on the server only, so the ref and its calls are dropped (
expose, for information).
A component whose root is a <component is> over tags gives a ref the element of whichever tag renders, and the ref follows it when the tag changes. Type it as the union of the tags' DOM interfaces, useTemplateRef<HTMLAnchorElement | HTMLButtonElement>(). Vue reads that element from the child's $el each time the ref is read, through toRef(() => …), since $el changes with the tag and Vue doesn't track it.
Exposed functions or the element
A ref on a component that calls defineExpose holds only what it exposes, never the element too. One ref has one value of one type, and merging functions onto an element would collide with its members: an exposed focus would hide the element's own. A component that wants a parent to reach its element exposes a function that acts on it, as SearchField's focus does above.
So a ref can't reach through a root component that exposes functions. On a component whose root is <SearchField> and that exposes nothing itself, a ref would hold SearchField's focus on most targets, which the component doesn't expose, and its root element on Vue. So a ref on it is UF3046. Expose a function from it too, or give it an element root.
The decisions behind this page are ADR-0049, ADR-0054, ADR-0118 and ADR-0122.
Fallthrough
Attributes, DOM listeners, class and style a component doesn't declare fall through to its root element, or to the element its rest is spread on.
Context
provide and inject share a value with every descendant under a key. Each framework gets its own context, from React's createContext to Angular's InjectionToken.