# Expose and component refs

> defineExpose lists the functions a parent calls through a component ref. A ref on a component that exposes nothing holds its root element.

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](/docs/components/template-refs-and-ids#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:

<!-- prettier-ignore -->
```tsx [SearchField.uf.tsx]
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>
  );
}
```

<!-- prettier-ignore -->
```tsx [Header.uf.tsx]
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 `?.`:

::framework-switcher

#react

<!-- prettier-ignore -->
```tsx [SearchField.tsx]
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>
  );
}

/** Joins class names, and the keys of an object's truthy entries, into one `className`. */
function cx(...parts: unknown[]): string {
  const names: string[] = [];
  for (const part of parts) {
    if (typeof part === "string") {
      if (part) names.push(part);
    } else if (part && typeof part === "object") {
      for (const [key, on] of Object.entries(part)) {
        if (on) names.push(key);
      }
    }
  }
  return names.join(" ");
}
```

<!-- prettier-ignore -->
```tsx [Header.tsx]
import SearchField from "./SearchField";
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>
  );
}

/** Joins class names, and the keys of an object's truthy entries, into one `className`. */
function cx(...parts: unknown[]): string {
  const names: string[] = [];
  for (const part of parts) {
    if (typeof part === "string") {
      if (part) names.push(part);
    } else if (part && typeof part === "object") {
      for (const [key, on] of Object.entries(part)) {
        if (on) names.push(key);
      }
    }
  }
  return names.join(" ");
}
```

#vue

<!-- prettier-ignore -->
```vue [SearchField.vue]
<script setup lang="ts">
import { useTemplateRef } from "vue";

const { label } = defineProps<{ label: string }>();

const input = useTemplateRef<HTMLInputElement>("input");

function focus() {
  input.value?.focus();
}

defineExpose({ focus });
</script>

<template>
  <label class="search">{{ label }}<input ref="input" type="search" /></label>
</template>
```

<!-- prettier-ignore -->
```vue [Header.vue]
<script setup lang="ts">
import SearchField from "./SearchField.vue";
import { useTemplateRef } from "vue";

const search = useTemplateRef<{ focus(): void }>("search");
</script>

<template>
  <header class="header">
    <SearchField ref="search" label="Find" />
    <button type="button" @click="search?.focus()">Search</button>
  </header>
</template>
```

#svelte

<!-- prettier-ignore -->
```svelte [SearchField.svelte]
<svelte:options runes={true} preserveWhitespace={false} />

<script lang="ts">
  import type { ClassValue, HTMLLabelAttributes } from "svelte/elements";

  type Props = Omit<HTMLLabelAttributes, "label" | "children" | "class" | "style"> & {
    label: string;
    class?: ClassValue;
    style?: string;
  };

  let { label, class: className, style, ...attributes }: Props = $props();

  let input: HTMLInputElement | null = null;

  export function focus() {
    input?.focus();
  }
</script>

<label
  class={["search", className]}
  {style}
  {...attributes}
>{label}<input bind:this={input} type="search" /></label>
```

<!-- prettier-ignore -->
```svelte [Header.svelte]
<svelte:options runes={true} preserveWhitespace={false} />

<script lang="ts">
  import SearchField from "./SearchField.svelte";
  import type { ClassValue, SvelteHTMLElements } from "svelte/elements";

  type Props = Omit<SvelteHTMLElements["header"], "children" | "class" | "style" | "ref"> & {
    class?: ClassValue;
    style?: string;
    ref?: HTMLElementTagNameMap["header"] | null;
  };

  let { class: className, style, ref = $bindable(null), ...attributes }: Props = $props();

  let search: { focus(): void } | null = null;
</script>

<header class={["header", className]} {style} bind:this={ref} {...attributes}>
  <SearchField bind:this={search} label="Find"
  /><button type="button" onclick={() => search?.focus()}>Search</button>
</header>
```

#angular

<!-- prettier-ignore -->
```ts [search-field.ts]
import { isPlatformBrowser } from "@angular/common";
import {
  Component,
  Directive,
  ElementRef,
  type OnChanges,
  type OnDestroy,
  type OnInit,
  PLATFORM_ID,
  Renderer2,
  inject,
  input as input_1,
  viewChild,
} from "@angular/core";

/** The scope attributes taken off each host, for the roots its component renders later. */
const scopes = new WeakMap<Element, string[]>();

/**
 * Gives a root node of its component the scope attributes the component's styled parents put on
 * its host (ADR-0063), and takes them off the host, which keeps only `display: contents`.
 */
@Directive({ selector: "[ufScope]" })
export class ScopeAttributes implements OnInit {
  readonly ufScope = input_1.required<HTMLElement>();
  private readonly element = inject<ElementRef<Element>>(ElementRef);
  private readonly renderer = inject(Renderer2);

  ngOnInit(): void {
    const host = this.ufScope();
    let names = scopes.get(host);
    if (!names) {
      names = host.getAttributeNames().filter((name) => name.startsWith("data-uf-"));
      for (const name of names) this.renderer.removeAttribute(host, name);
      scopes.set(host, names);
    }
    for (const name of names) this.renderer.setAttribute(this.element.nativeElement, name, "");
  }
}

/** A native listener of each event a consumer passes, by the event's name (ADR-0118). */
type Listeners = { [K in keyof HTMLElementEventMap]?: (event: HTMLElementEventMap[K]) => void };

/**
 * Puts what a consumer passes the component, and the component does not declare, on the element
 * that takes it (ADR-0118): the attributes, the consumer's winning over the element's own, and
 * the native listeners, which run after the element's own.
 */
@Directive({ selector: "[ufFallthrough]" })
export class Fallthrough implements OnChanges, OnDestroy {
  readonly ufFallthrough = input_1.required<{
    attributes: Record<string, unknown> | undefined;
    listeners: Listeners | undefined;
  }>();
  private readonly element = inject<ElementRef<Element>>(ElementRef);
  private readonly renderer = inject(Renderer2);
  private readonly browser = isPlatformBrowser(inject(PLATFORM_ID));
  private readonly listening = new Map<string, { handler: unknown; stop: () => void }>();
  private written: Record<string, unknown> = {};

  ngOnChanges(): void {
    const element = this.element.nativeElement;
    const { attributes = {}, listeners = {} } = this.ufFallthrough();
    for (const name of Object.keys(this.written)) {
      if (!(name in attributes)) this.renderer.removeAttribute(element, name);
    }
    for (const [name, value] of Object.entries(attributes)) {
      if (value === null || value === undefined) this.renderer.removeAttribute(element, name);
      else this.renderer.setAttribute(element, name, String(value));
    }
    this.written = attributes;
    if (!this.browser) return;
    const handlers = new Map(Object.entries(listeners));
    for (const [event, { handler, stop }] of this.listening) {
      if (handlers.get(event) === handler) continue;
      stop();
      this.listening.delete(event);
    }
    for (const [event, handler] of handlers) {
      if (handler === undefined || this.listening.has(event)) continue;
      this.listening.set(event, { handler, stop: this.renderer.listen(element, event, handler) });
    }
  }

  ngOnDestroy(): void {
    for (const { stop } of this.listening.values()) stop();
  }
}

@Component({
  selector: "uf-search-field",
  imports: [ScopeAttributes, Fallthrough],
  host: { "[attr.class]": "null", "[attr.style]": "'display: contents;'" },
  preserveWhitespaces: false,
  template: `
    @let label = this.label();
    <label
      class="search"
      [class]="this.class()"
      [style]="this.style()"
      [ufFallthrough]="{ attributes: this.ufAttributes(), listeners: this.ufListeners() }"
      [ufScope]="this.host"
    >{{ label }}<input #input type="search" /></label>
  `,
})
export default class SearchField {
  readonly label = input_1.required<string>();
  readonly class = input_1<string>();
  readonly style = input_1<Record<string, string | null | undefined>>();
  readonly ufAttributes = input_1<Record<string, unknown>>();
  readonly ufListeners = input_1<Listeners>();
  private readonly input = viewChild<ElementRef<HTMLInputElement>>("input");

  focus() {
    this.input()?.nativeElement.focus();
  }
  protected readonly host = inject<ElementRef<HTMLElement>>(ElementRef).nativeElement;
}
```

<!-- prettier-ignore -->
```ts [header.ts]
import SearchField from "./search-field";
import { isPlatformBrowser } from "@angular/common";
import {
  Component,
  Directive,
  ElementRef,
  type OnChanges,
  type OnDestroy,
  type OnInit,
  PLATFORM_ID,
  Renderer2,
  inject,
  input,
  viewChild,
} from "@angular/core";

/** The scope attributes taken off each host, for the roots its component renders later. */
const scopes = new WeakMap<Element, string[]>();

/**
 * Gives a root node of its component the scope attributes the component's styled parents put on
 * its host (ADR-0063), and takes them off the host, which keeps only `display: contents`.
 */
@Directive({ selector: "[ufScope]" })
export class ScopeAttributes implements OnInit {
  readonly ufScope = input.required<HTMLElement>();
  private readonly element = inject<ElementRef<Element>>(ElementRef);
  private readonly renderer = inject(Renderer2);

  ngOnInit(): void {
    const host = this.ufScope();
    let names = scopes.get(host);
    if (!names) {
      names = host.getAttributeNames().filter((name) => name.startsWith("data-uf-"));
      for (const name of names) this.renderer.removeAttribute(host, name);
      scopes.set(host, names);
    }
    for (const name of names) this.renderer.setAttribute(this.element.nativeElement, name, "");
  }
}

/** A native listener of each event a consumer passes, by the event's name (ADR-0118). */
type Listeners = { [K in keyof HTMLElementEventMap]?: (event: HTMLElementEventMap[K]) => void };

/**
 * Puts what a consumer passes the component, and the component does not declare, on the element
 * that takes it (ADR-0118): the attributes, the consumer's winning over the element's own, and
 * the native listeners, which run after the element's own.
 */
@Directive({ selector: "[ufFallthrough]" })
export class Fallthrough implements OnChanges, OnDestroy {
  readonly ufFallthrough = input.required<{
    attributes: Record<string, unknown> | undefined;
    listeners: Listeners | undefined;
  }>();
  private readonly element = inject<ElementRef<Element>>(ElementRef);
  private readonly renderer = inject(Renderer2);
  private readonly browser = isPlatformBrowser(inject(PLATFORM_ID));
  private readonly listening = new Map<string, { handler: unknown; stop: () => void }>();
  private written: Record<string, unknown> = {};

  ngOnChanges(): void {
    const element = this.element.nativeElement;
    const { attributes = {}, listeners = {} } = this.ufFallthrough();
    for (const name of Object.keys(this.written)) {
      if (!(name in attributes)) this.renderer.removeAttribute(element, name);
    }
    for (const [name, value] of Object.entries(attributes)) {
      if (value === null || value === undefined) this.renderer.removeAttribute(element, name);
      else this.renderer.setAttribute(element, name, String(value));
    }
    this.written = attributes;
    if (!this.browser) return;
    const handlers = new Map(Object.entries(listeners));
    for (const [event, { handler, stop }] of this.listening) {
      if (handlers.get(event) === handler) continue;
      stop();
      this.listening.delete(event);
    }
    for (const [event, handler] of handlers) {
      if (handler === undefined || this.listening.has(event)) continue;
      this.listening.set(event, { handler, stop: this.renderer.listen(element, event, handler) });
    }
  }

  ngOnDestroy(): void {
    for (const { stop } of this.listening.values()) stop();
  }
}

@Component({
  selector: "uf-header",
  imports: [SearchField, ScopeAttributes, Fallthrough],
  host: { "[attr.class]": "null", "[attr.style]": "'display: contents;'" },
  preserveWhitespaces: false,
  template: `
    <header
      class="header"
      [class]="this.class()"
      [style]="this.style()"
      [ufFallthrough]="{ attributes: this.ufAttributes(), listeners: this.ufListeners() }"
      [ufScope]="this.host"
      #ufElement
    >
      <uf-search-field #search [label]="'Find'" />
      <button type="button" (click)="onSearch()">Search</button>
    </header>
  `,
})
export default class Header {
  readonly class = input<string>();
  readonly style = input<Record<string, string | null | undefined>>();
  readonly ufAttributes = input<Record<string, unknown>>();
  readonly ufListeners = input<Listeners>();
  private readonly search = viewChild<{ focus(): void }>("search");
  readonly ufElement = viewChild<ElementRef<HTMLElement>>("ufElement");

  protected onSearch() {
    this.search()?.focus();
  }
  protected readonly host = inject<ElementRef<HTMLElement>>(ElementRef).nativeElement;
}
```

#solid

<!-- prettier-ignore -->
```tsx [SearchField.tsx]
import { type ComponentProps, type JSX, onCleanup, splitProps, untrack } from "solid-js";

export default function SearchField(
  props: { label: string } & Omit<ComponentProps<"label">, "label" | "ref" | "style"> & {
      style?: JSX.CSSProperties;
      ref?: (api: { focus: () => void }) => void;
    },
) {
  const [, others] = splitProps(props, ["label", "ref", "class"]);

  let input: HTMLInputElement | null = null;

  function focus() {
    input?.focus();
  }

  untrack(() => props.ref?.({ focus }));

  return (
    <label class={props.class ? `search ${props.class}` : "search"} {...others}>
      {props.label}
      <input
        ref={(element) => {
          input = element;
          onCleanup(() => {
            input = null;
          });
        }}
        type="search"
      />
    </label>
  );
}
```

<!-- prettier-ignore -->
```tsx [Header.tsx]
import SearchField from "./SearchField";
import { type ComponentProps, type JSX, onCleanup, splitProps } from "solid-js";

export default function Header(
  props: Omit<ComponentProps<"header">, "style"> & { style?: JSX.CSSProperties },
) {
  const [, others] = splitProps(props, ["class"]);

  let search: { focus(): void } | null = null;

  return (
    <header class={props.class ? `header ${props.class}` : "header"} {...others}>
      <SearchField
        ref={(api) => {
          search = api;
          onCleanup(() => {
            search = null;
          });
        }}
        label="Find"
      />
      <button type="button" onClick={() => search?.focus()}>
        Search
      </button>
    </header>
  );
}
```

#qwik

<!-- prettier-ignore -->
```tsx [SearchField.tsx]
import {
  $,
  type CSSProperties,
  type ClassList,
  type PropsOf,
  type Signal,
  component$,
  useSignal,
  useTask$,
  useVisibleTask$,
} from "@qwik.dev/core";

export default component$<
  { label: string } & Omit<PropsOf<"label">, "label" | "class" | "style" | "ref"> & {
      class?: ClassList;
      style?: CSSProperties;
      ref?: Signal<object | undefined>;
    }
>(({ label, class: className, style, ref, ...attributes }) => {
  const input = useSignal<HTMLInputElement>();

  const focus = $(() => {
    input.value?.focus();
  });

  useTask$(() => {
    exposeRef(ref, { focus });
  });
  useVisibleTask$(
    ({ cleanup }) => {
      cleanup(() => exposeRef(ref, undefined));
    },
    { strategy: "document-ready" },
  );

  return (
    <label class={["search", className]} style={style} {...attributes}>
      {label}
      <input ref={input} type="search" />
    </label>
  );
});

/**
 * Fills a consumer's component ref with what the component exposes, or empties it: Qwik has no
 * component instance for the ref to hold (ADR-0054).
 */
function exposeRef(ref: Signal<object | undefined> | undefined, exposed: object | undefined): void {
  if (ref) ref.value = exposed;
}
```

<!-- prettier-ignore -->
```tsx [Header.tsx]
import SearchField from "./SearchField";
import {
  type CSSProperties,
  type ClassList,
  type PropsOf,
  component$,
  useSignal,
} from "@qwik.dev/core";

export default component$<
  Omit<PropsOf<"header">, "class" | "style"> & { class?: ClassList; style?: CSSProperties }
>(({ class: className, style, ...attributes }) => {
  const search = useSignal<{ focus(): void }>();

  return (
    <header class={["header", className]} style={style} {...attributes}>
      <SearchField ref={search} label="Find" />
      <button type="button" onClick$={() => search.value?.focus()}>
        Search
      </button>
    </header>
  );
});
```

#astro

<!-- prettier-ignore -->
```astro [SearchField.astro]
---
import type { HTMLAttributes } from "astro/types";

interface Props extends Omit<HTMLAttributes<"label">, "label"> {
  label: string;
  class?: string;
  style?: Record<string, string | number | undefined>;
}

const { label, class: className, style, ...attrs } = Astro.props;
---

<label
  class:list={["search", className]}
  style={style}
  {...attrs}
>{label}<input type="search" /></label>
```

<!-- prettier-ignore -->
```astro [Header.astro]
---
import SearchField from "./SearchField.astro";
import type { HTMLAttributes } from "astro/types";

interface Props extends HTMLAttributes<"header"> {
  class?: string;
  style?: Record<string, string | number | undefined>;
}

const { class: className, style, ...attrs } = Astro.props;
---

<header class:list={["header", className]} style={style} {...attrs}>
  <SearchField label="Find" />
  <button type="button">Search</button>
</header>
```

::

- React passes the ref as a prop, `ref`, which the child fills with `useImperativeHandle`. The child exports the handle's type, `SearchFieldHandle`, and the parent reads `search.current`.
- Vue writes `defineExpose`, and the parent `useTemplateRef("search")` with `ref="search"`.
- Svelte exports each function from the component, `export function focus()`, and the parent binds a `let` with `bind: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 with `viewChild`.
- Solid passes a `ref` callback, which the child calls with what it exposes, and the parent empties its `let` with `onCleanup`.
- 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`](/docs/reference/targets#capabilities), 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](/docs/reference/diagnostics#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](/docs/reference/diagnostics#UF3046). A ref on a component that exposes nothing holds its root element ([below](#a-ref-on-a-component-that-exposes-nothing)).

## Several functions

A component may expose several functions, declared with `function` or as an arrow function:

<!-- prettier-ignore -->
```tsx [Counter.uf.tsx]
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](/docs/components/template-refs-and-ids#where-to-read-one)).

## 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](/docs/components/fallthrough#refs)). Type it as that element's DOM interface, by its name:

<!-- prettier-ignore -->
```tsx [NameField.uf.tsx]
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} />;
}
```

<!-- prettier-ignore -->
```tsx [Bio.uf.tsx]
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} />;
}
```

<!-- prettier-ignore -->
```tsx [Profile.uf.tsx]
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](/docs/reference/diagnostics#UF3046).

::framework-switcher

#react

<!-- prettier-ignore -->
```tsx [NameField.tsx]
import {
  type ComponentPropsWithRef,
  type Ref,
  type RefCallback,
  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}
    />
  );
}

/** Joins an element's refs into one ref callback, whose cleanup clears each. */
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();
    };
  };
}
```

<!-- prettier-ignore -->
```tsx [Profile.tsx]
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>
  );
}
```

#vue

<!-- prettier-ignore -->
```vue [NameField.vue]
<script setup lang="ts">
import { onMounted, ref, useTemplateRef } from "vue";

const { label } = defineProps<{ label: string }>();

const input = useTemplateRef<HTMLInputElement>("input");
const mounted = ref(false);

onMounted(() => {
  mounted.value = input.value !== null;
});

function fill() {
  if (input.value && !input.value.value && mounted.value) input.value.value = "Ada";
}
</script>

<template>
  <input ref="input" name="name" :aria-label="label" @focus="fill" />
</template>
```

<!-- prettier-ignore -->
```vue [Profile.vue]
<script setup lang="ts">
import Bio from "./Bio.vue";
import NameField from "./NameField.vue";
import { computed, useTemplateRef } from "vue";

const nameComponent = useTemplateRef<{ $el: HTMLInputElement }>("nameComponent");
const name = computed(() => nameComponent.value?.$el ?? null);

const bioComponent = useTemplateRef<{ $el: HTMLInputElement }>("bioComponent");
const bio = computed(() => bioComponent.value?.$el ?? null);
</script>

<template>
  <form aria-label="Profile">
    <NameField ref="nameComponent" label="Name" />
    <button type="button" @click="name?.focus()">Edit name</button>
    <Bio ref="bioComponent" label="Bio" />
    <button type="button" @click="bio?.focus()">Edit bio</button>
  </form>
</template>
```

#svelte

<!-- prettier-ignore -->
```svelte [NameField.svelte]
<svelte:options runes={true} preserveWhitespace={false} />

<script lang="ts">
  import { onMount } from "svelte";
  import type { ClassValue, HTMLInputAttributes } from "svelte/elements";

  type Props = Omit<HTMLInputAttributes, "label" | "children" | "class" | "style" | "ref"> & {
    label: string;
    class?: ClassValue;
    style?: string;
    ref?: HTMLElementTagNameMap["input"] | null;
  };

  let {
    label,
    class: className,
    style,
    ref = $bindable(null),
    onfocus,
    ...attributes
  }: Props = $props();

  let input: HTMLInputElement | null = null;
  let mounted = $state(false);

  onMount(() => {
    mounted = input !== null;
  });

  function fill() {
    if (input && !input.value && mounted) input.value = "Ada";
  }
</script>

<input
  bind:this={() => input, (element) => {
    input = element;
    ref = element;
  }}
  name="name"
  aria-label={label}
  onfocus={(event) => {
    fill();
    onfocus?.(event);
  }}
  class={className}
  {style}
  {...attributes}
/>
```

<!-- prettier-ignore -->
```svelte [Profile.svelte]
<svelte:options runes={true} preserveWhitespace={false} />

<script lang="ts">
  import Bio from "./Bio.svelte";
  import NameField from "./NameField.svelte";
  import type { ClassValue, HTMLFormAttributes } from "svelte/elements";

  type Props = Omit<HTMLFormAttributes, "children" | "class" | "style" | "ref"> & {
    class?: ClassValue;
    style?: string;
    ref?: HTMLElementTagNameMap["form"] | null;
  };

  let { class: className, style, ref = $bindable(null), ...attributes }: Props = $props();

  let name = $state<HTMLInputElement | null>(null);
  let bio = $state<HTMLInputElement | null>(null);
</script>

<form aria-label="Profile" class={className} {style} bind:this={ref} {...attributes}>
  <NameField bind:ref={name} label="Name"
  /><button type="button" onclick={() => name?.focus()}>Edit name</button
  ><Bio bind:ref={bio} label="Bio"
  /><button type="button" onclick={() => bio?.focus()}>Edit bio</button>
</form>
```

#angular

<!-- prettier-ignore -->
```ts [name-field.ts]
import { isPlatformBrowser } from "@angular/common";
import {
  Component,
  Directive,
  ElementRef,
  type OnChanges,
  type OnDestroy,
  type OnInit,
  PLATFORM_ID,
  Renderer2,
  afterNextRender,
  inject,
  input as input_1,
  signal,
  viewChild,
} from "@angular/core";

/** The scope attributes taken off each host, for the roots its component renders later. */
const scopes = new WeakMap<Element, string[]>();

/**
 * Gives a root node of its component the scope attributes the component's styled parents put on
 * its host (ADR-0063), and takes them off the host, which keeps only `display: contents`.
 */
@Directive({ selector: "[ufScope]" })
export class ScopeAttributes implements OnInit {
  readonly ufScope = input_1.required<HTMLElement>();
  private readonly element = inject<ElementRef<Element>>(ElementRef);
  private readonly renderer = inject(Renderer2);

  ngOnInit(): void {
    const host = this.ufScope();
    let names = scopes.get(host);
    if (!names) {
      names = host.getAttributeNames().filter((name) => name.startsWith("data-uf-"));
      for (const name of names) this.renderer.removeAttribute(host, name);
      scopes.set(host, names);
    }
    for (const name of names) this.renderer.setAttribute(this.element.nativeElement, name, "");
  }
}

/** A native listener of each event a consumer passes, by the event's name (ADR-0118). */
type Listeners = { [K in keyof HTMLElementEventMap]?: (event: HTMLElementEventMap[K]) => void };

/**
 * Puts what a consumer passes the component, and the component does not declare, on the element
 * that takes it (ADR-0118): the attributes, the consumer's winning over the element's own, and
 * the native listeners, which run after the element's own.
 */
@Directive({ selector: "[ufFallthrough]" })
export class Fallthrough implements OnChanges, OnDestroy {
  readonly ufFallthrough = input_1.required<{
    attributes: Record<string, unknown> | undefined;
    listeners: Listeners | undefined;
  }>();
  private readonly element = inject<ElementRef<Element>>(ElementRef);
  private readonly renderer = inject(Renderer2);
  private readonly browser = isPlatformBrowser(inject(PLATFORM_ID));
  private readonly listening = new Map<string, { handler: unknown; stop: () => void }>();
  private written: Record<string, unknown> = {};

  ngOnChanges(): void {
    const element = this.element.nativeElement;
    const { attributes = {}, listeners = {} } = this.ufFallthrough();
    for (const name of Object.keys(this.written)) {
      if (!(name in attributes)) this.renderer.removeAttribute(element, name);
    }
    for (const [name, value] of Object.entries(attributes)) {
      if (value === null || value === undefined) this.renderer.removeAttribute(element, name);
      else this.renderer.setAttribute(element, name, String(value));
    }
    this.written = attributes;
    if (!this.browser) return;
    const handlers = new Map(Object.entries(listeners));
    for (const [event, { handler, stop }] of this.listening) {
      if (handlers.get(event) === handler) continue;
      stop();
      this.listening.delete(event);
    }
    for (const [event, handler] of handlers) {
      if (handler === undefined || this.listening.has(event)) continue;
      this.listening.set(event, { handler, stop: this.renderer.listen(element, event, handler) });
    }
  }

  ngOnDestroy(): void {
    for (const { stop } of this.listening.values()) stop();
  }
}

@Component({
  selector: "uf-name-field",
  imports: [ScopeAttributes, Fallthrough],
  host: { "[attr.class]": "null", "[attr.style]": "'display: contents;'" },
  preserveWhitespaces: false,
  template: `
    @let label = this.label();
    <input
      #input
      name="name"
      [attr.aria-label]="'aria-label' in (this.ufAttributes() ?? {}) ? this.ufAttributes()?.['aria-label'] : label"
      (focus)="fill()"
      [class]="this.class()"
      [style]="this.style()"
      [ufFallthrough]="{ attributes: this.ufAttributes(), listeners: this.ufListeners() }"
      [ufScope]="this.host"
      #ufElement
    />
  `,
})
export default class NameField {
  readonly label = input_1.required<string>();
  readonly class = input_1<string>();
  readonly style = input_1<Record<string, string | null | undefined>>();
  readonly ufAttributes = input_1<Record<string, unknown>>();
  readonly ufListeners = input_1<Listeners>();
  private readonly input = viewChild<ElementRef<HTMLInputElement>>("input");
  readonly ufElement = viewChild<ElementRef<HTMLInputElement>>("ufElement");
  private readonly mounted = signal(false);

  constructor() {
    afterNextRender(() => {
      this.mounted.set((this.input()?.nativeElement ?? null) !== null);
    });
  }

  protected fill() {
    if (this.input()?.nativeElement && !this.input()!.nativeElement.value && this.mounted())
      this.input()!.nativeElement.value = "Ada";
  }
  protected readonly host = inject<ElementRef<HTMLElement>>(ElementRef).nativeElement;
}
```

<!-- prettier-ignore -->
```ts [profile.ts]
import Bio from "./bio";
import NameField from "./name-field";
import { isPlatformBrowser } from "@angular/common";
import {
  Component,
  Directive,
  ElementRef,
  type OnChanges,
  type OnDestroy,
  type OnInit,
  PLATFORM_ID,
  Renderer2,
  computed,
  inject,
  input,
  viewChild,
} from "@angular/core";

/** The scope attributes taken off each host, for the roots its component renders later. */
const scopes = new WeakMap<Element, string[]>();

/**
 * Gives a root node of its component the scope attributes the component's styled parents put on
 * its host (ADR-0063), and takes them off the host, which keeps only `display: contents`.
 */
@Directive({ selector: "[ufScope]" })
export class ScopeAttributes implements OnInit {
  readonly ufScope = input.required<HTMLElement>();
  private readonly element = inject<ElementRef<Element>>(ElementRef);
  private readonly renderer = inject(Renderer2);

  ngOnInit(): void {
    const host = this.ufScope();
    let names = scopes.get(host);
    if (!names) {
      names = host.getAttributeNames().filter((name) => name.startsWith("data-uf-"));
      for (const name of names) this.renderer.removeAttribute(host, name);
      scopes.set(host, names);
    }
    for (const name of names) this.renderer.setAttribute(this.element.nativeElement, name, "");
  }
}

/** A native listener of each event a consumer passes, by the event's name (ADR-0118). */
type Listeners = { [K in keyof HTMLElementEventMap]?: (event: HTMLElementEventMap[K]) => void };

/**
 * Puts what a consumer passes the component, and the component does not declare, on the element
 * that takes it (ADR-0118): the attributes, the consumer's winning over the element's own, and
 * the native listeners, which run after the element's own.
 */
@Directive({ selector: "[ufFallthrough]" })
export class Fallthrough implements OnChanges, OnDestroy {
  readonly ufFallthrough = input.required<{
    attributes: Record<string, unknown> | undefined;
    listeners: Listeners | undefined;
  }>();
  private readonly element = inject<ElementRef<Element>>(ElementRef);
  private readonly renderer = inject(Renderer2);
  private readonly browser = isPlatformBrowser(inject(PLATFORM_ID));
  private readonly listening = new Map<string, { handler: unknown; stop: () => void }>();
  private written: Record<string, unknown> = {};

  ngOnChanges(): void {
    const element = this.element.nativeElement;
    const { attributes = {}, listeners = {} } = this.ufFallthrough();
    for (const name of Object.keys(this.written)) {
      if (!(name in attributes)) this.renderer.removeAttribute(element, name);
    }
    for (const [name, value] of Object.entries(attributes)) {
      if (value === null || value === undefined) this.renderer.removeAttribute(element, name);
      else this.renderer.setAttribute(element, name, String(value));
    }
    this.written = attributes;
    if (!this.browser) return;
    const handlers = new Map(Object.entries(listeners));
    for (const [event, { handler, stop }] of this.listening) {
      if (handlers.get(event) === handler) continue;
      stop();
      this.listening.delete(event);
    }
    for (const [event, handler] of handlers) {
      if (handler === undefined || this.listening.has(event)) continue;
      this.listening.set(event, { handler, stop: this.renderer.listen(element, event, handler) });
    }
  }

  ngOnDestroy(): void {
    for (const { stop } of this.listening.values()) stop();
  }
}

@Component({
  selector: "uf-profile",
  imports: [NameField, Bio, ScopeAttributes, Fallthrough],
  host: { "[attr.class]": "null", "[attr.style]": "'display: contents;'" },
  preserveWhitespaces: false,
  template: `
    <form
      aria-label="Profile"
      [class]="this.class()"
      [style]="this.style()"
      [ufFallthrough]="{ attributes: this.ufAttributes(), listeners: this.ufListeners() }"
      [ufScope]="this.host"
      #ufElement
    >
      <uf-name-field #name [label]="'Name'" />
      <button type="button" (click)="onEditName()">Edit name</button>
      <uf-bio #bio [label]="'Bio'" />
      <button type="button" (click)="onEditBio()">Edit bio</button>
    </form>
  `,
})
export default class Profile {
  readonly class = input<string>();
  readonly style = input<Record<string, string | null | undefined>>();
  readonly ufAttributes = input<Record<string, unknown>>();
  readonly ufListeners = input<Listeners>();
  private readonly nameComponent = viewChild("name", { read: NameField });
  private readonly name = computed<ElementRef<HTMLInputElement> | undefined>(() =>
    this.nameComponent()?.ufElement(),
  );
  private readonly bioComponent = viewChild("bio", { read: Bio });
  private readonly bio = computed<ElementRef<HTMLInputElement> | undefined>(() =>
    this.bioComponent()?.ufElement(),
  );
  readonly ufElement = viewChild<ElementRef<HTMLFormElement>>("ufElement");

  protected onEditName() {
    this.name()?.nativeElement.focus();
  }

  protected onEditBio() {
    this.bio()?.nativeElement.focus();
  }
  protected readonly host = inject<ElementRef<HTMLElement>>(ElementRef).nativeElement;
}
```

#solid

<!-- prettier-ignore -->
```tsx [NameField.tsx]
import {
  type ComponentProps,
  type JSX,
  createSignal,
  onCleanup,
  onMount,
  splitProps,
} from "solid-js";

export default function NameField(
  props: { label: string } & Omit<ComponentProps<"input">, "label" | "style" | "onFocus"> & {
      style?: JSX.CSSProperties;
      onFocus?: Extract<ComponentProps<"input">["onFocus"], (event: never) => void>;
    },
) {
  const [, others] = splitProps(props, ["label", "onFocus"]);

  let input: HTMLInputElement | null = null;
  const [mounted, setMounted] = createSignal(false);

  onMount(() => {
    setMounted(input !== null);
  });

  function fill() {
    if (input && !input.value && mounted()) input.value = "Ada";
  }

  return (
    <input
      ref={(element) => {
        input = element;
        onCleanup(() => {
          input = null;
        });
      }}
      name="name"
      aria-label={props.label}
      onFocus={(event) => {
        fill();
        props.onFocus?.(event);
      }}
      {...others}
    />
  );
}
```

<!-- prettier-ignore -->
```tsx [Profile.tsx]
import Bio from "./Bio";
import NameField from "./NameField";
import { type ComponentProps, type JSX, onCleanup } from "solid-js";

export default function Profile(
  props: Omit<ComponentProps<"form">, "style"> & { style?: JSX.CSSProperties },
) {
  let name: HTMLInputElement | null = null;
  let bio: HTMLInputElement | null = null;

  return (
    <form aria-label="Profile" {...props}>
      <NameField
        ref={(element) => {
          name = element;
          onCleanup(() => {
            name = null;
          });
        }}
        label="Name"
      />
      <button type="button" onClick={() => name?.focus()}>
        Edit name
      </button>
      <Bio
        ref={(element) => {
          bio = element;
          onCleanup(() => {
            bio = null;
          });
        }}
        label="Bio"
      />
      <button type="button" onClick={() => bio?.focus()}>
        Edit bio
      </button>
    </form>
  );
}
```

#qwik

<!-- prettier-ignore -->
```tsx [NameField.tsx]
import {
  $,
  type CSSProperties,
  type ClassList,
  type PropsOf,
  type Signal,
  component$,
  useSignal,
  useVisibleTask$,
} from "@qwik.dev/core";

export default component$<
  { label: string } & Omit<PropsOf<"input">, "label" | "class" | "style" | "ref"> & {
      class?: ClassList;
      style?: CSSProperties;
      ref?: Signal<Element | undefined>;
    }
>(({ label, class: className, style, onFocus$, ref, ...attributes }) => {
  const input = useSignal<HTMLInputElement>();
  const mounted = useSignal(false);

  useVisibleTask$(
    () => {
      mounted.value = (input.value ?? null) !== null;
    },
    { strategy: "document-ready" },
  );

  const fill = $(() => {
    if (input.value && !input.value.value && mounted.value) input.value.value = "Ada";
  });

  return (
    <input
      ref={(element) => {
        input.value = element;
        if (ref) ref.value = element;
      }}
      name="name"
      aria-label={label}
      onFocus$={[fill, onFocus$]}
      class={className}
      style={style}
      {...attributes}
    />
  );
});
```

<!-- prettier-ignore -->
```tsx [Profile.tsx]
import Bio from "./Bio";
import NameField from "./NameField";
import {
  type CSSProperties,
  type ClassList,
  type PropsOf,
  component$,
  useSignal,
} from "@qwik.dev/core";

export default component$<
  Omit<PropsOf<"form">, "class" | "style"> & { class?: ClassList; style?: CSSProperties }
>(({ class: className, style, ...attributes }) => {
  const name = useSignal<HTMLInputElement>();
  const bio = useSignal<HTMLInputElement>();

  return (
    <form aria-label="Profile" class={className} style={style} {...attributes}>
      <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>
  );
});
```

#astro

<!-- prettier-ignore -->
```astro [NameField.astro]
---
import type { HTMLAttributes } from "astro/types";

interface Props extends Omit<HTMLAttributes<"input">, "label"> {
  label: string;
  class?: string;
  style?: Record<string, string | number | undefined>;
}

const { label, class: className, style, name, "aria-label": ariaLabel, ...attrs } = Astro.props;
---

<input
  name={"name" in Astro.props ? name : "name"}
  aria-label={"aria-label" in Astro.props ? ariaLabel : label}
  class:list={[className]}
  style={style}
  {...attrs}
/>
```

<!-- prettier-ignore -->
```astro [Profile.astro]
---
import Bio from "./Bio.astro";
import NameField from "./NameField.astro";
import type { HTMLAttributes } from "astro/types";

interface Props extends HTMLAttributes<"form"> {
  class?: string;
  style?: Record<string, string | number | undefined>;
}

const { class: className, style, "aria-label": ariaLabel, ...attrs } = Astro.props;
---

<form
  aria-label={"aria-label" in Astro.props ? ariaLabel : "Profile"}
  class:list={[className]}
  style={style}
  {...attrs}
>
  <NameField label="Name" />
  <button type="button">Edit name</button>
  <Bio label="Bio" />
  <button type="button">Edit bio</button>
</form>
```

::

- React passes the ref as React 19's `ref` prop, which reaches the root element. Where the root has a ref of its own, an inline helper, `mergeRefs`, joins the two into one ref callback, made once per pair with `useMemo`. The parent's ref is `useRef<HTMLInputElement>(null)`.
- Vue holds the child's instance, `useTemplateRef<{ $el: HTMLInputElement }>("nameComponent")`, and the parent's ref is a `computed` of its `$el`, the root element.
- Svelte gives the child a `$bindable` `ref` prop, `ref?: HTMLElementTagNameMap["input"] | null`, which its root binds beside its own ref through a function binding. The parent binds it to a `$state` ref, `bind:ref={name}`.
- Angular's host is no element a ref may hold, so the child declares `ufElement`, a `viewChild` of its root, `ElementRef<HTMLInputElement>`. The parent reads the child with `viewChild("name", { read: NameField })`, and its ref is a `computed` of that `ufElement` ([`expose`](/docs/reference/targets#capabilities), emulated).
- Solid passes a `ref` callback, which the child's spread hands the root element, beside the root's own `ref` callback.
- 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](/docs/components/fallthrough#a-component-is-root) 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](/docs/reference/diagnostics#UF3046). Expose a function from it too, or give it an element root.

The decisions behind this page are [ADR-0049](https://github.com/uxfront-com/unframework/blob/main/docs/adrs/0049-template-refs-and-ids.md), [ADR-0054](https://github.com/uxfront-com/unframework/blob/main/docs/adrs/0054-composition-on-every-target.md), [ADR-0118](https://github.com/uxfront-com/unframework/blob/main/docs/adrs/0118-attributes-listeners-and-refs-fall-through.md) and [ADR-0122](https://github.com/uxfront-com/unframework/blob/main/docs/adrs/0122-a-dynamic-root-takes-what-every-tag-takes.md).
