# Expose and component refs

> defineExpose lists the functions a parent may call through a template ref. Each framework exposes them its own way, like React's imperative handle.

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 CSSProperties, type Ref, useImperativeHandle, useRef } from "react";

export interface SearchFieldHandle {
  focus(): void;
}

export interface SearchFieldAttributes {
  className?: string;
  style?: CSSProperties;
  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} {...scopeAttributes(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(" ");
}

/** The scope attributes of the styled parents that render this component, for its root. */
function scopeAttributes(props: object): Record<string, ""> {
  const scope: Record<string, ""> = {};
  for (const key of Object.keys(props)) {
    if (key.startsWith("data-uf-")) scope[key] = "";
  }
  return scope;
}
```

<!-- prettier-ignore -->
```tsx [Header.tsx]
import SearchField from "./SearchField";
import { type CSSProperties, useRef } from "react";

export interface HeaderAttributes {
  className?: string;
  style?: CSSProperties;
}

export default function Header({ className, style, ...attributes }: HeaderAttributes) {
  const search = useRef<{ focus(): void }>(null);

  return (
    <header className={cx("header", className)} style={style} {...scopeAttributes(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(" ");
}

/** The scope attributes of the styled parents that render this component, for its root. */
function scopeAttributes(props: object): Record<string, ""> {
  const scope: Record<string, ""> = {};
  for (const key of Object.keys(props)) {
    if (key.startsWith("data-uf-")) scope[key] = "";
  }
  return scope;
}
```

#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 } from "svelte/elements";

  type Props = { label: string; class?: ClassValue; style?: string };

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

  let input: HTMLInputElement | null = null;

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

  /** The scope attributes of the styled parents that render this component, for its root. */
  function scopeAttributes(props: object): Record<string, ""> {
    const scope: Record<string, ""> = {};
    for (const name of Object.keys(props)) if (name.startsWith("data-uf-")) scope[name] = "";
    return scope;
  }
</script>

<label
  class={["search", className]}
  {style}
  {...scopeAttributes(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 } from "svelte/elements";

  type Props = { class?: ClassValue; style?: string };

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

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

  /** The scope attributes of the styled parents that render this component, for its root. */
  function scopeAttributes(props: object): Record<string, ""> {
    const scope: Record<string, ""> = {};
    for (const name of Object.keys(props)) if (name.startsWith("data-uf-")) scope[name] = "";
    return scope;
  }
</script>

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

#angular

<!-- prettier-ignore -->
```ts [search-field.ts]
import {
  Component,
  Directive,
  ElementRef,
  type OnInit,
  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, "");
  }
}

@Component({
  selector: "uf-search-field",
  imports: [ScopeAttributes],
  host: { "[attr.class]": "null", "[attr.style]": "'display: contents;'" },
  preserveWhitespaces: false,
  template: `
    @let label = this.label();
    <label
      class="search"
      [class]="this.class()"
      [style]="this.style()"
      [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>>();
  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 {
  Component,
  Directive,
  ElementRef,
  type OnInit,
  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, "");
  }
}

@Component({
  selector: "uf-header",
  imports: [SearchField, ScopeAttributes],
  host: { "[attr.class]": "null", "[attr.style]": "'display: contents;'" },
  preserveWhitespaces: false,
  template: `
    <header class="header" [class]="this.class()" [style]="this.style()" [ufScope]="this.host">
      <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>>();
  private readonly search = viewChild<{ focus(): void }>("search");

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

#solid

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

export default function SearchField(
  props: { label: string } & {
    class?: string;
    style?: JSX.CSSProperties;
    ref?: (api: { focus: () => void }) => void;
  },
) {
  let input: HTMLInputElement | null = null;

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

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

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

/** The scope attributes of the styled parents that render this component, for its root. */
function scopeAttributes(props: object): Record<string, ""> {
  const scope: Record<string, ""> = {};
  for (const name of Object.keys(props)) if (name.startsWith("data-uf-")) scope[name] = "";
  return scope;
}
```

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

export default function Header(props: { class?: string; style?: JSX.CSSProperties }) {
  let search: { focus(): void } | null = null;

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

/** The scope attributes of the styled parents that render this component, for its root. */
function scopeAttributes(props: object): Record<string, ""> {
  const scope: Record<string, ""> = {};
  for (const name of Object.keys(props)) if (name.startsWith("data-uf-")) scope[name] = "";
  return scope;
}
```

#qwik

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

export default component$<
  { label: string } & { 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]} {...scopeAttributes(attributes)} style={style}>
      {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;
}

/** The scope attributes of the styled parents that render this component, for its root. */
function scopeAttributes(props: object): Record<string, ""> {
  const scope: Record<string, ""> = {};
  for (const key of Object.keys(props)) {
    if (key.startsWith("data-uf-")) scope[key] = "";
  }
  return scope;
}
```

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

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

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

/** The scope attributes of the styled parents that render this component, for its root. */
function scopeAttributes(props: object): Record<string, ""> {
  const scope: Record<string, ""> = {};
  for (const key of Object.keys(props)) {
    if (key.startsWith("data-uf-")) scope[key] = "";
  }
  return scope;
}
```

#astro

<!-- prettier-ignore -->
```astro [SearchField.astro]
---
interface Props {
  label: string;
  class?: string;
  style?: Record<string, string | number | undefined>;
}

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

/** The scope attributes of the styled parents that render this component, for its root. */
function scopeAttributes(props: object): Record<string, ""> {
  const scope: Record<string, ""> = {};
  for (const name of Object.keys(props)) if (name.startsWith("data-uf-")) scope[name] = "";
  return scope;
}
---

<label
  class:list={["search", className]}
  style={style}
  {...scopeAttributes(Astro.props)}
>{label}<input type="search" /></label>
```

<!-- prettier-ignore -->
```astro [Header.astro]
---
import SearchField from "./SearchField.astro";

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

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

/** The scope attributes of the styled parents that render this component, for its root. */
function scopeAttributes(props: object): Record<string, ""> {
  const scope: Record<string, ""> = {};
  for (const name of Object.keys(props)) if (name.startsWith("data-uf-")) scope[name] = "";
  return scope;
}
---

<header class:list={["header", className]} style={style} {...scopeAttributes(Astro.props)}>
  <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 on a component that exposes nothing, or whose type names a function the component doesn't expose, is [UF3046](/docs/reference/diagnostics#UF3046).

## 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)).

The decisions behind this page are [ADR-0049](https://github.com/uxfront-com/unframework/blob/main/docs/adrs/0049-template-refs-and-ids.md) and [ADR-0054](https://github.com/uxfront-com/unframework/blob/main/docs/adrs/0054-composition-on-every-target.md).
