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

A parent often needs to reach the element inside a component it doesn't own: give a button an `id` that a label points at, describe it with `aria-describedby`, tag it for a test, listen to its `focus` or give it some margin. So what a parent passes a component, and the component doesn't declare, falls through to the component's root element. It's Vue's rule, and every target follows it.

This page walks you through it. We'll look at:

- the attributes that fall through, and the ones that don't
- the DOM listeners that fall through
- `class` and `style`, which merge with the root's own
- a component whose root is another component
- a ref on a component that exposes nothing
- `...rest`, which puts all of it on another element
- turning fallthrough off, and the components that can't take it

## What falls through

Let's start with the rule. A component declares its props, its models, its slots and the events it lists in `defineEmits`. Everything else a parent passes it falls through:

- **Attributes**, like `id`, `aria-*`, `data-*` or `type`, land on its root element.
- **Listeners** of DOM events, like `onClick` or `onFocus`, listen on its root element.
- **`class` and `style`** merge with the root element's own.

The root element is the one element the component renders at its top. A root that is a component passes all of it on to that component, which places it by the same rule.

A declared prop never falls through, so a prop named like an attribute stays a prop. Where the root element sets an attribute the parent passes too, the parent's value wins. `key` is no attribute, and a `ref` holds the root element ([Refs](#refs)).

Pass a prop by its own name. `aria-label` on a component that declares `ariaLabel` is [UF3035](/docs/reference/diagnostics#UF3035), with a fix to `ariaLabel`, since Vue would give it to the prop and the other targets would put it on the root element. The same goes for a model's name.

## Attributes

Here a parent passes a button an `id`, two ARIA attributes, a test id and a `type`. The button declares only `title`:

<!-- prettier-ignore -->
```tsx [SaveButton.uf.tsx]
// Declares one prop, `title`, which it renders as text: a declared prop never falls through.
export default function SaveButton({ title }: { title: string }) {
  return (
    <button type="button" class="button">
      {title}
    </button>
  );
}
```

<!-- prettier-ignore -->
```tsx [Editor.uf.tsx]
import { ref } from "@uxfront/unframework";

import SaveButton from "./SaveButton.uf.tsx";

export default function Editor() {
  const pressed = ref(false);
  return (
    <div class="editor">
      <p id="save-hint">Saves the draft.</p>
      <SaveButton
        title="Save"
        id="save"
        aria-describedby="save-hint"
        aria-pressed={pressed.value}
        data-testid="save-button"
        type="submit"
        class="primary"
      />
      <button type="button" onClick={() => (pressed.value = !pressed.value)}>
        Toggle
      </button>
    </div>
  );
}
```

`title` is a prop `SaveButton` declares and renders as text, so it never reaches the `<button>` as an attribute. Everything else lands on the `<button>`: the `id`, the ARIA attributes, the `data-testid` and the `type`, where the parent's `submit` wins over the button's own `button`. The bound `aria-pressed` follows `pressed` as it changes. The corpus records the rendered DOM this way, with each text node in quotes:

<!-- prettier-ignore -->
```html
<div class="editor">
  <p id="save-hint">
    "Saves the draft."
  </p>
  <button aria-describedby="save-hint" aria-pressed="false" class="button primary" data-testid="save-button" id="save" type="submit">
    "Save"
  </button>
  <button type="button">
    "Toggle"
  </button>
</div>
```

The parent checks each attribute as one of that element's own, so the element's rules hold: HTML's names, the values an enumerated attribute allows and ARIA's ([Attributes](/docs/components/attributes)). A name that is no prop of the child and no attribute of its root element is [UF3035](/docs/reference/diagnostics#UF3035), with a fix to the closest prop or attribute, like `type` for `tpye`.

::framework-switcher

#react

<!-- prettier-ignore -->
```tsx [SaveButton.tsx]
import type { ComponentPropsWithRef } from "react";

export type SaveButtonAttributes = Omit<ComponentPropsWithRef<"button">, "title" | "children">;

export default function SaveButton({
  title,
  className,
  style,
  ...attributes
}: { title: string } & SaveButtonAttributes) {
  return (
    <button type="button" className={cx("button", className)} style={style} {...attributes}>
      {title}
    </button>
  );
}

/** 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 [Editor.tsx]
import SaveButton from "./SaveButton";
import { type ComponentPropsWithRef, useRef, useState } from "react";

export type EditorAttributes = Omit<ComponentPropsWithRef<"div">, "children">;

export default function Editor({ className, style, ...attributes }: EditorAttributes) {
  const [pressed, setPressed] = useState(false);
  const pressedRef = useRef(pressed);

  return (
    <div className={cx("editor", className)} style={style} {...attributes}>
      <p id="save-hint">Saves the draft.</p>
      <SaveButton
        title="Save"
        className="primary"
        id="save"
        aria-describedby="save-hint"
        aria-pressed={pressed}
        data-testid="save-button"
        type="submit"
      />
      <button
        type="button"
        onClick={() => {
          pressedRef.current = !pressedRef.current;
          setPressed(pressedRef.current);
        }}
      >
        Toggle
      </button>
    </div>
  );
}

/** 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 [SaveButton.vue]
<script setup lang="ts">
const { title } = defineProps<{ title: string }>();
</script>

<template>
  <button type="button" class="button">{{ title }}</button>
</template>
```

<!-- prettier-ignore -->
```vue [Editor.vue]
<script setup lang="ts">
import SaveButton from "./SaveButton.vue";
import { ref } from "vue";

const pressed = ref(false);
</script>

<template>
  <div class="editor">
    <p id="save-hint">Saves the draft.</p>
    <SaveButton
      id="save"
      title="Save"
      aria-describedby="save-hint"
      :aria-pressed="pressed"
      data-testid="save-button"
      type="submit"
      class="primary"
    />
    <button type="button" @click="pressed = !pressed">Toggle</button>
  </div>
</template>
```

#svelte

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

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

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

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

<button
  type="button"
  class={["button", className]}
  {style}
  bind:this={ref}
  {...attributes}
>{title}</button>
```

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

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

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

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

  let pressed = $state(false);
</script>

<div class={["editor", className]} {style} bind:this={ref} {...attributes}>
  <p id="save-hint">Saves the draft.</p
  ><SaveButton
    title="Save"
    id="save"
    aria-describedby="save-hint"
    aria-pressed={pressed}
    data-testid="save-button"
    type="submit"
    class="primary"
  /><button type="button" onclick={() => (pressed = !pressed)}>Toggle</button>
</div>
```

#angular

<!-- prettier-ignore -->
```ts [save-button.ts]
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-save-button",
  imports: [ScopeAttributes, Fallthrough],
  host: { "[attr.class]": "null", "[attr.style]": "'display: contents;'" },
  preserveWhitespaces: false,
  template: `
    @let title = this.title();
    <button
      type="button"
      class="button"
      [class]="this.class()"
      [style]="this.style()"
      [ufFallthrough]="{ attributes: this.ufAttributes(), listeners: this.ufListeners() }"
      [ufScope]="this.host"
      #ufElement
    >{{ title }}</button>
  `,
})
export default class SaveButton {
  readonly title = input.required<string>();
  readonly class = input<string>();
  readonly style = input<Record<string, string | null | undefined>>();
  readonly ufAttributes = input<Record<string, unknown>>();
  readonly ufListeners = input<Listeners>();
  readonly ufElement = viewChild<ElementRef<HTMLButtonElement>>("ufElement");
  protected readonly host = inject<ElementRef<HTMLElement>>(ElementRef).nativeElement;
}
```

<!-- prettier-ignore -->
```ts [editor.ts]
import SaveButton from "./save-button";
import { isPlatformBrowser } from "@angular/common";
import {
  Component,
  Directive,
  ElementRef,
  type OnChanges,
  type OnDestroy,
  type OnInit,
  PLATFORM_ID,
  Renderer2,
  inject,
  input,
  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.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-editor",
  imports: [SaveButton, ScopeAttributes, Fallthrough],
  host: { "[attr.class]": "null", "[attr.style]": "'display: contents;'" },
  preserveWhitespaces: false,
  template: `
    @let pressed = this.pressed();
    <div
      class="editor"
      [class]="this.class()"
      [style]="this.style()"
      [ufFallthrough]="{ attributes: this.ufAttributes(), listeners: this.ufListeners() }"
      [ufScope]="this.host"
      #ufElement
    >
      <p id="save-hint">Saves the draft.</p>
      <uf-save-button
        [title]="'Save'"
        [class]="'primary'"
        [ufAttributes]="{ id: 'save', 'aria-describedby': 'save-hint', 'aria-pressed': pressed, 'data-testid': 'save-button', type: 'submit' }"
      />
      <button type="button" (click)="onToggle()">Toggle</button>
    </div>
  `,
})
export default class Editor {
  readonly class = input<string>();
  readonly style = input<Record<string, string | null | undefined>>();
  readonly ufAttributes = input<Record<string, unknown>>();
  readonly ufListeners = input<Listeners>();
  readonly ufElement = viewChild<ElementRef<HTMLDivElement>>("ufElement");
  protected readonly pressed = signal(false);

  protected onToggle() {
    this.pressed.set(!this.pressed());
  }
  protected readonly host = inject<ElementRef<HTMLElement>>(ElementRef).nativeElement;
}
```

#solid

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

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

  return (
    <button type="button" class={props.class ? `button ${props.class}` : "button"} {...others}>
      {props.title}
    </button>
  );
}
```

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

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

  const [pressed, setPressed] = createSignal(false);

  return (
    <div class={props.class ? `editor ${props.class}` : "editor"} {...others}>
      <p id="save-hint">Saves the draft.</p>
      <SaveButton
        title="Save"
        id="save"
        aria-describedby="save-hint"
        aria-pressed={pressed()}
        data-testid="save-button"
        type="submit"
        class="primary"
      />
      <button type="button" onClick={() => setPressed(!pressed())}>
        Toggle
      </button>
    </div>
  );
}
```

#qwik

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

export default component$<
  { title: string } & Omit<PropsOf<"button">, "title" | "class" | "style"> & {
      class?: ClassList;
      style?: CSSProperties;
    }
>(({ title, class: className, style, ...attributes }) => {
  return (
    <button type="button" class={["button", className]} style={style} {...attributes}>
      {title}
    </button>
  );
});
```

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

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

  return (
    <div class={["editor", className]} style={style} {...attributes}>
      <p id="save-hint">Saves the draft.</p>
      <SaveButton
        title="Save"
        id="save"
        aria-describedby="save-hint"
        aria-pressed={pressed.value}
        data-testid="save-button"
        type="submit"
        class={["primary"]}
      />
      <button type="button" onClick$={() => (pressed.value = !pressed.value)}>
        Toggle
      </button>
    </div>
  );
});
```

#astro

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

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

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

<button
  type={"type" in Astro.props ? type : "button"}
  class:list={["button", className]}
  style={style}
  {...attrs}
>{title}</button>
```

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

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

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

const pressed = false as boolean;
---

<div class:list={["editor", className]} style={style} {...attrs}>
  <p id="save-hint">Saves the draft.</p>
  <SaveButton
    title="Save"
    id="save"
    aria-describedby="save-hint"
    aria-pressed={pressed}
    data-testid="save-button"
    type="submit"
    class="primary"
  />
  <button type="button">Toggle</button>
</div>
```

::

- React types what falls through as the root element's own props without the declared ones, `SaveButtonAttributes`, and the root spreads the props' rest, `{...attributes}`, after its own attributes, so the parent's win. A parent writes them in React's spelling for that element, like `className` or `tabIndex`.
- Vue passes them on by itself, as its own `$attrs`.
- Svelte types the props with the root element's attributes from `svelte/elements`, without the component's own names, and the root spreads the props' rest, `{...attributes}`, last.
- Angular has no attribute spread, and a host element that carries an attribute isn't unwrapped ([The Angular host](/docs/reference/targets#the-angular-host)). So each component declares two more inputs: `ufAttributes`, a record of attributes by name, and `ufListeners`, a record of listeners by event. The parent binds them on the host, `[ufAttributes]="{ id: 'save', … }"`, which keeps no attribute. The root binds an inline attribute directive, `Fallthrough` (`[ufFallthrough]`), which sets and removes the attributes through `Renderer2`, on the server and in the browser, the parent's winning ([`fallthrough`](/docs/reference/targets#capabilities), emulated). Where the root binds an attribute of its own that the parent passes too, like `[attr.aria-label]`, it binds the parent's value whenever the record holds that name, so the parent's still wins after the root's own value changes. A hand-written Angular parent that writes `id="save"` on `<uf-save-button>` puts it on the host, so it binds `[ufAttributes]="{ id: 'save' }"` instead.
- Solid takes the declared props out with `splitProps`, and the root spreads the others after its own attributes, so the parent's win.
- Qwik types the props with the root element's own, `Omit<PropsOf<"button">, …>`, and the root spreads the props' rest last.
- Astro spreads the rest of `Astro.props` last on the root. Astro writes every attribute it is given and the browser [keeps the first of two](https://html.spec.whatwg.org/multipage/parsing.html#parse-error-duplicate-attribute), so the root tests whether the parent passed each of its own attributes, `"type" in Astro.props ? type : "button"`. The parent's value wins whenever it passes the key, even as `undefined`, which removes the attribute, as Vue does. A bare boolean attribute Astro doesn't know, like `multiple`, passes on as `""`, so the element writes it bare.

So every output but Vue's types and spreads what falls through on each component with one root element, and you'll see it on every page of these docs, even where no parent passes anything. The rest the root spreads also carries a styled parent's `data-uf-*` scope attribute, so the parent's stylesheet reaches the root ([Styles](/docs/components/styles#the-childs-root)).

## Listeners

Next, let's look at listeners. Here a parent listens to a chip's `click`, `focus` and `keydown`, and to `pick`, the one event the chip declares:

<!-- prettier-ignore -->
```tsx [Chip.uf.tsx]
import { defineEmits } from "@uxfront/unframework";

// Declares one event, `pick`, which its own click emits: a consumer's `onClick` is a native
// listener beside it.
export default function Chip({ label }: { label: string }) {
  const emit = defineEmits<{ pick: [label: string] }>();
  return (
    <button type="button" class="chip" onClick={() => emit("pick", label)}>
      {label}
    </button>
  );
}
```

<!-- prettier-ignore -->
```tsx [Picker.uf.tsx]
import { ref } from "@uxfront/unframework";

import Chip from "./Chip.uf.tsx";

export default function Picker() {
  const log = ref<string[]>([]);

  function record(line: string) {
    log.value = [...log.value, line];
  }

  return (
    <section aria-label="Picker">
      <Chip
        label="Ada"
        onClick={(event) => record(`click on ${(event.currentTarget as Element).localName}`)}
        onPick={(label) => record(`pick ${label}`)}
        onFocus={(event) => record(`focus on ${(event.currentTarget as Element).localName}`)}
        onKeydown={(event) =>
          record(`keydown ${event.key} on ${(event.currentTarget as Element).localName}`)
        }
      />
      <ol aria-label="Log">
        {log.value.map((entry, index) => (
          <li key={index}>{entry}</li>
        ))}
      </ol>
    </section>
  );
}
```

`onClick`, `onFocus` and `onKeydown` aren't events `Chip` declares, so they're native listeners on its `<button>`, typed as that element's own would be: the `onKeydown` handler receives a `KeyboardEvent`. Where the root listens to the same event itself, both run, the root's own first, as Vue merges them. Each of the parent's listeners logs its event's `currentTarget`, the element it listens on. So tab to the chip, press `a` and click it, and the log reads "focus on button", "keydown a on button", "pick Ada" and "click on button": the listeners are on the `<button>` itself, not on an element around it.

An `onX` that is neither an event the child declares nor a DOM event is [UF3036](/docs/reference/diagnostics#UF3036), with a fix to the closest event, one the child declares or a DOM event, like `onClick` for `onClik`. A listener option on a listener that falls through, like `onClickOnce`, is [UF1002](/docs/reference/diagnostics#UF1002).

::framework-switcher

#react

<!-- prettier-ignore -->
```tsx [Chip.tsx]
import type { ComponentPropsWithRef } from "react";

export interface ChipEvents {
  onPick?: (label: string) => void;
}

export type ChipAttributes = Omit<ComponentPropsWithRef<"button">, "label" | "onPick" | "children">;

export default function Chip({
  label,
  onPick,
  className,
  style,
  onClick,
  ...attributes
}: { label: string } & ChipEvents & ChipAttributes) {
  return (
    <button
      type="button"
      className={cx("chip", className)}
      onClick={(event) => {
        onPick?.(label);
        onClick?.(event);
      }}
      style={style}
      {...attributes}
    >
      {label}
    </button>
  );
}

/** 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 [Chip.vue]
<script setup lang="ts">
const { label } = defineProps<{ label: string }>();
const emit = defineEmits<{ pick: [label: string] }>();
</script>

<template>
  <button type="button" class="chip" @click="emit('pick', label)">{{ label }}</button>
</template>
```

#svelte

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

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

  type Props = Omit<
    HTMLButtonAttributes,
    "label" | "onpick" | "children" | "class" | "style" | "ref"
  > & {
    label: string;
    onpick?: (label: string) => void;
    class?: ClassValue;
    style?: string;
    ref?: HTMLElementTagNameMap["button"] | null;
  };

  let {
    label,
    onpick,
    class: className,
    style,
    ref = $bindable(null),
    onclick,
    ...attributes
  }: Props = $props();
</script>

<button
  type="button"
  class={["chip", className]}
  onclick={(event) => {
    onpick?.(label);
    onclick?.(event);
  }}
  {style}
  bind:this={ref}
  {...attributes}
>{label}</button>
```

#angular

<!-- prettier-ignore -->
```ts [chip.ts]
import { isPlatformBrowser } from "@angular/common";
import {
  Component,
  Directive,
  ElementRef,
  type OnChanges,
  type OnDestroy,
  type OnInit,
  PLATFORM_ID,
  Renderer2,
  inject,
  input,
  output,
  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-chip",
  imports: [ScopeAttributes, Fallthrough],
  host: { "[attr.class]": "null", "[attr.style]": "'display: contents;'" },
  preserveWhitespaces: false,
  template: `
    @let label = this.label();
    <button
      type="button"
      class="chip"
      (click)="pick.emit(label)"
      [class]="this.class()"
      [style]="this.style()"
      [ufFallthrough]="{ attributes: this.ufAttributes(), listeners: this.ufListeners() }"
      [ufScope]="this.host"
      #ufElement
    >{{ label }}</button>
  `,
})
export default class Chip {
  readonly label = input.required<string>();
  readonly class = input<string>();
  readonly style = input<Record<string, string | null | undefined>>();
  readonly ufAttributes = input<Record<string, unknown>>();
  readonly ufListeners = input<Listeners>();
  readonly pick = output<string>();
  readonly ufElement = viewChild<ElementRef<HTMLButtonElement>>("ufElement");
  protected readonly host = inject<ElementRef<HTMLElement>>(ElementRef).nativeElement;
}
```

#solid

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

export interface ChipEvents {
  onPick?: (label: string) => void;
}

export default function Chip(
  props: { label: string } & ChipEvents &
    Omit<ComponentProps<"button">, "label" | "style" | "onClick"> & {
      style?: JSX.CSSProperties;
      onClick?: Extract<ComponentProps<"button">["onClick"], (event: never) => void>;
    },
) {
  const [, others] = splitProps(props, ["label", "onPick", "class", "onClick"]);

  return (
    <button
      type="button"
      class={props.class ? `chip ${props.class}` : "chip"}
      onClick={(event) => {
        props.onPick?.(props.label);
        props.onClick?.(event);
      }}
      {...others}
    >
      {props.label}
    </button>
  );
}
```

#qwik

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

export interface ChipEvents {
  onPick$?: QRL<(label: string) => void>;
}

export default component$<
  { label: string } & ChipEvents &
    Omit<PropsOf<"button">, "label" | "onPick$" | "class" | "style"> & {
      class?: ClassList;
      style?: CSSProperties;
    }
>(({ label, onPick$, class: className, style, onClick$, ...attributes }) => {
  return (
    <button
      type="button"
      class={["chip", className]}
      onClick$={[$(() => onPick$?.(label)), onClick$]}
      style={style}
      {...attributes}
    >
      {label}
    </button>
  );
});
```

#astro

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

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

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

<button
  type={"type" in Astro.props ? type : "button"}
  class:list={["chip", className]}
  style={style}
  {...attrs}
>{label}</button>
```

::

- React takes the parent's `onClick` out of the props' rest and calls it from the root's own handler, after it emits `pick`. That handler takes the event type React gives the prop, so the parent's handler gets the same event. React's `onFocus` also hears focus that moves inside an element, so the parent's React output checks `event.target` to keep the DOM's `focus`. A listener whose React prop wouldn't keep the DOM's meaning on that element is [UF1002](/docs/reference/diagnostics#UF1002) on React: `change` on a text field, `focusin`, `focusout`, `select` and `beforeinput`.
- Vue merges the parent's listener with the root's own by itself.
- Svelte takes `onclick` out of the props' rest and calls it from the root's own handler, after its own code.
- Angular's parent binds `[ufListeners]="{ click: …, focus: …, keydown: … }"` on the host, and `Fallthrough` adds each listener with `Renderer2.listen` in the browser, after the element's own.
- Solid takes `onClick` out with `splitProps` and calls it from the root's own handler, after its own code.
- Qwik passes the root an array of both, `onClick$={[$(() => onPick$?.(label)), onClick$]}`, which runs the root's own first, and the parent's `event.currentTarget` reads Qwik's second parameter, the element. Where the root listens in the capture phase or passively, the parent's listener stays out of that group, so it runs in the bubble phase and its `preventDefault()` works. A `preventDefault()` at the top of the parent's listener runs in a `sync$` handler, not as a `preventdefault:` attribute, since a root that listens from the window would apply that attribute to the event anywhere on the page.
- Astro renders on the server only, so no listener runs: the output drops it, and the compiler reports it for information ([`interactivity`](/docs/reference/targets#capabilities)).

## Class and style

Now let's look at `class` and `style`. A component with one root element takes them like any attribute it doesn't declare, and the parent passes them as it would to an element, static or bound:

<!-- prettier-ignore -->
```tsx [Tag.uf.tsx]
export default function Tag({ label }: { label: string }) {
  return (
    <span class="tag" style="padding: 2px 6px; color: rgb(30, 30, 30)">
      {label}
    </span>
  );
}
```

<!-- prettier-ignore -->
```tsx [Tags.uf.tsx]
import { ref } from "@uxfront/unframework";

import Tag from "./Tag.uf.tsx";

export default function Tags() {
  const active = ref(false);
  return (
    <div class="tags">
      <Tag label="plain" />
      <Tag label="wide" class="wide" style="margin-left: 8px" />
      <Tag
        label="toggled"
        class={["picked", { active: active.value }]}
        style={{ color: active.value ? "rgb(200, 0, 0)" : undefined }}
      />
      <button type="button" onClick={() => (active.value = !active.value)}>
        Toggle
      </button>
    </div>
  );
}
```

Unlike the other attributes, they merge with the root's own rather than replace them. The root's class is the union of both sets of names: `tag wide`, or `tag picked active`. For a style property both set, the parent's declaration wins, and a property the parent sets to `null` or `undefined` is removed from the root, as an object merge does. So while `active` is false, the toggled tag has no `color` at all.

::framework-switcher

#react

<!-- prettier-ignore -->
```tsx [Tag.tsx]
import type { ComponentPropsWithRef } from "react";

export type TagAttributes = Omit<ComponentPropsWithRef<"span">, "label" | "children">;

export default function Tag({
  label,
  className,
  style,
  ...attributes
}: { label: string } & TagAttributes) {
  return (
    <span
      className={cx("tag", className)}
      style={{ padding: "2px 6px", color: "rgb(30, 30, 30)", ...style }}
      {...attributes}
    >
      {label}
    </span>
  );
}

/** 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 [Tags.tsx]
import Tag from "./Tag";
import { type ComponentPropsWithRef, useRef, useState } from "react";

export type TagsAttributes = Omit<ComponentPropsWithRef<"div">, "children">;

export default function Tags({ className, style, ...attributes }: TagsAttributes) {
  const [active, setActive] = useState(false);
  const activeRef = useRef(active);

  return (
    <div className={cx("tags", className)} style={style} {...attributes}>
      <Tag label="plain" />
      <Tag label="wide" className="wide" style={{ marginLeft: "8px" }} />
      <Tag
        label="toggled"
        className={cx("picked", { active })}
        style={{ color: active ? "rgb(200, 0, 0)" : undefined }}
      />
      <button
        type="button"
        onClick={() => {
          activeRef.current = !activeRef.current;
          setActive(activeRef.current);
        }}
      >
        Toggle
      </button>
    </div>
  );
}

/** 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 [Tag.vue]
<script setup lang="ts">
const { label } = defineProps<{ label: string }>();
</script>

<template>
  <span class="tag" style="padding: 2px 6px; color: rgb(30, 30, 30)">{{ label }}</span>
</template>
```

<!-- prettier-ignore -->
```vue [Tags.vue]
<script setup lang="ts">
import Tag from "./Tag.vue";
import { ref } from "vue";

const active = ref(false);
</script>

<template>
  <div class="tags">
    <Tag label="plain" />
    <Tag label="wide" class="wide" style="margin-left: 8px" />
    <Tag
      label="toggled"
      class="picked"
      :class="{ active }"
      :style="{ color: active ? 'rgb(200, 0, 0)' : undefined }"
    />
    <button type="button" @click="active = !active">Toggle</button>
  </div>
</template>
```

#svelte

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

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

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

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

  function mergeStyle(
    own: Record<string, string | number | null | undefined>,
    consumer: string | undefined,
  ): string {
    const merged = { ...own };
    const text = consumer ?? "";
    const add = (declaration: string) => {
      const colon = declaration.indexOf(":");
      if (colon > 0)
        merged[declaration.slice(0, colon).trim()] = declaration.slice(colon + 1).trim();
    };
    let start = 0;
    let depth = 0;
    let quote = "";
    for (let index = 0; index < text.length; index++) {
      const char = text[index];
      if (quote) {
        if (char === "\\") index++;
        else if (char === quote) quote = "";
      } else if (char === "\\") index++;
      else if (char === "/" && text[index + 1] === "*") {
        const close = text.indexOf("*/", index + 2);
        index = close === -1 ? text.length : close + 1;
      } else if (char === '"' || char === "'") quote = char;
      else if (char === "(") depth++;
      else if (char === ")") depth--;
      else if (char === ";" && depth === 0) {
        add(text.slice(start, index));
        start = index + 1;
      }
    }
    add(text.slice(start));
    return Object.entries(merged)
      .map(([property, value]) => `${property}: ${value ?? ""}`)
      .join("; ");
  }
</script>

<span
  class={["tag", className]}
  style={mergeStyle({ padding: "2px 6px", color: "rgb(30, 30, 30)" }, style)}
  bind:this={ref}
  {...attributes}
>{label}</span>
```

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

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

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

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

  let active = $state(false);
</script>

<div class={["tags", className]} {style} bind:this={ref} {...attributes}>
  <Tag label="plain" /><Tag label="wide" class="wide" style="margin-left: 8px"
  /><Tag
    label="toggled"
    class={["picked", { active }]}
    style="color: {active ? "rgb(200, 0, 0)" : undefined}"
  /><button type="button" onclick={() => (active = !active)}>Toggle</button>
</div>
```

#angular

<!-- prettier-ignore -->
```ts [tag.ts]
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-tag",
  imports: [ScopeAttributes, Fallthrough],
  host: { "[attr.class]": "null", "[attr.style]": "'display: contents;'" },
  preserveWhitespaces: false,
  template: `
    @let label = this.label();
    <span
      class="tag"
      [style]="{ padding: '2px 6px', color: 'rgb(30, 30, 30)', ...this.style() }"
      [class]="this.class()"
      [ufFallthrough]="{ attributes: this.ufAttributes(), listeners: this.ufListeners() }"
      [ufScope]="this.host"
      #ufElement
    >{{ label }}</span>
  `,
})
export default class Tag {
  readonly label = input.required<string>();
  readonly class = input<string>();
  readonly style = input<Record<string, string | null | undefined>>();
  readonly ufAttributes = input<Record<string, unknown>>();
  readonly ufListeners = input<Listeners>();
  readonly ufElement = viewChild<ElementRef<HTMLSpanElement>>("ufElement");
  protected readonly host = inject<ElementRef<HTMLElement>>(ElementRef).nativeElement;
}
```

<!-- prettier-ignore -->
```ts [tags.ts]
import Tag from "./tag";
import { isPlatformBrowser } from "@angular/common";
import {
  Component,
  Directive,
  ElementRef,
  type OnChanges,
  type OnDestroy,
  type OnInit,
  PLATFORM_ID,
  Renderer2,
  inject,
  input,
  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.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-tags",
  imports: [Tag, ScopeAttributes, Fallthrough],
  host: { "[attr.class]": "null", "[attr.style]": "'display: contents;'" },
  preserveWhitespaces: false,
  template: `
    @let active = this.active();
    <div
      class="tags"
      [class]="this.class()"
      [style]="this.style()"
      [ufFallthrough]="{ attributes: this.ufAttributes(), listeners: this.ufListeners() }"
      [ufScope]="this.host"
      #ufElement
    >
      <uf-tag [label]="'plain'" />
      <uf-tag [label]="'wide'" [class]="'wide'" [style]="{ 'margin-left': '8px' }" />
      <uf-tag
        [label]="'toggled'"
        [class]="['picked', active ? 'active' : null].join(' ')"
        [style]="{ color: active ? 'rgb(200, 0, 0)' : undefined }"
      />
      <button type="button" (click)="onToggle()">Toggle</button>
    </div>
  `,
})
export default class Tags {
  readonly class = input<string>();
  readonly style = input<Record<string, string | null | undefined>>();
  readonly ufAttributes = input<Record<string, unknown>>();
  readonly ufListeners = input<Listeners>();
  readonly ufElement = viewChild<ElementRef<HTMLDivElement>>("ufElement");
  protected readonly active = signal(false);

  protected onToggle() {
    this.active.set(!this.active());
  }
  protected readonly host = inject<ElementRef<HTMLElement>>(ElementRef).nativeElement;
}
```

#solid

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

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

  return (
    <span
      class={props.class ? `tag ${props.class}` : "tag"}
      style={{ ...{ padding: "2px 6px", color: "rgb(30, 30, 30)" }, ...props.style }}
      {...others}
    >
      {props.label}
    </span>
  );
}
```

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

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

  const [active, setActive] = createSignal(false);

  return (
    <div class={props.class ? `tags ${props.class}` : "tags"} {...others}>
      <Tag label="plain" />
      <Tag label="wide" class="wide" style={{ "margin-left": "8px" }} />
      <Tag
        label="toggled"
        class={cx("picked", { active: active() })}
        style={{ color: active() ? "rgb(200, 0, 0)" : undefined }}
      />
      <button type="button" onClick={() => setActive(!active())}>
        Toggle
      </button>
    </div>
  );
}

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

#qwik

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

export default component$<
  { label: string } & Omit<PropsOf<"span">, "label" | "class" | "style"> & {
      class?: ClassList;
      style?: CSSProperties;
    }
>(({ label, class: className, style, ...attributes }) => {
  return (
    <span
      class={["tag", className]}
      style={{ padding: "2px 6px", color: "rgb(30, 30, 30)", ...style }}
      {...attributes}
    >
      {label}
    </span>
  );
});
```

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

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

  return (
    <div class={["tags", className]} style={style} {...attributes}>
      <Tag label="plain" />
      <Tag label="wide" class={["wide"]} style={{ marginLeft: "8px" }} />
      <Tag
        label="toggled"
        class={["picked", { active: Boolean(active.value) }]}
        style={{ color: active.value ? "rgb(200, 0, 0)" : undefined }}
      />
      <button type="button" onClick$={() => (active.value = !active.value)}>
        Toggle
      </button>
    </div>
  );
});
```

#astro

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

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

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

<span
  class:list={["tag", className]}
  style={{ padding: "2px 6px", color: "rgb(30, 30, 30)", ...style }}
  {...attrs}
>{label}</span>
```

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

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

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

const active = false as boolean;
---

<div class:list={["tags", className]} style={style} {...attrs}>
  <Tag label="plain" />
  <Tag label="wide" class="wide" style={{ marginLeft: "8px" }} />
  <Tag
    label="toggled"
    class:list={["picked", { active }]}
    style={{ color: active ? "rgb(200, 0, 0)" : undefined }}
  />
  <button type="button">Toggle</button>
</div>
```

::

- React, Solid, Qwik and Astro merge the class and the style into the root: the class through `cx` on React, a template string on Solid, an array on Qwik and `class:list` on Astro, the style by spreading the parent's object over the root's own.
- Vue passes both on by itself.
- Svelte declares `class` and `style` props too. A Svelte `style` is a string, which can't unset a property, so where the root has a style of its own an inline helper, `mergeStyle`, merges the parent's declarations over it and drops the root's declaration of a property the parent left empty ([`fallthrough`](/docs/reference/targets#capabilities), emulated). A root with no style of its own takes `{style}` as it is.
- Angular declares `class` and `style` inputs, merges them into the root, and clears them from its host element, which keeps only `display: contents`. A parent binds them, `[class]="'wide'"`, so they reach the inputs.

## Through a component root

A component whose root is another component passes everything on to that component's root. Here `SaveAction` renders `Pressable`, whose root is a `<button>`, and a toolbar passes `SaveAction` an `id`, an `aria-label`, a listener and a ref:

<!-- prettier-ignore -->
```tsx [Pressable.uf.tsx]
// The root element: a button with a class of its own.
export default function Pressable({ text }: { text: string }) {
  return (
    <button type="button" class="pressable">
      {text}
    </button>
  );
}
```

<!-- prettier-ignore -->
```tsx [SaveAction.uf.tsx]
import Pressable from "./Pressable.uf.tsx";

// Its root is a component: what its consumer passes passes on to that component's root.
export default function SaveAction({ text }: { text: string }) {
  return <Pressable text={text} class="save" />;
}
```

<!-- prettier-ignore -->
```tsx [Toolbar.uf.tsx]
import { ref, useTemplateRef } from "@uxfront/unframework";

import SaveAction from "./SaveAction.uf.tsx";

export default function Toolbar() {
  const clicks = ref(0);
  const save = useTemplateRef<HTMLButtonElement>();
  return (
    <div role="toolbar" aria-label="Actions">
      <SaveAction
        ref={save}
        text="Save"
        id="save"
        aria-label="Save draft"
        onClick={() => clicks.value++}
      />
      <button type="button" onClick={() => save.value?.focus()}>
        Focus save
      </button>
      <p>Clicks: {clicks.value}</p>
    </div>
  );
}
```

The attributes land on `Pressable`'s `<button>`, beside the class `SaveAction` passes it. A click on it runs the toolbar's handler, and the ref holds it, so "Focus save" focuses it:

<!-- prettier-ignore -->
```html
<div aria-label="Actions" role="toolbar">
  <button aria-label="Save draft" class="pressable save" id="save" type="button">
    "Save"
  </button>
  <button type="button">
    "Focus save"
  </button>
  <p>
    "Clicks: 0"
  </p>
</div>
```

A class merges all the way down: `<SaveAction text="Save" class="wide" />` renders `<button class="pressable save wide">`.

::framework-switcher

#react

<!-- prettier-ignore -->
```tsx [SaveAction.tsx]
import Pressable from "./Pressable";
import type { ComponentPropsWithRef } from "react";

export type SaveActionAttributes = Omit<
  ComponentPropsWithRef<typeof Pressable>,
  "text" | "children"
>;

export default function SaveAction({
  text,
  className,
  style,
  ...attributes
}: { text: string } & SaveActionAttributes) {
  return <Pressable text={text} className={cx("save", className)} style={style} {...attributes} />;
}

/** 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 [SaveAction.vue]
<script setup lang="ts">
import Pressable from "./Pressable.vue";

const { text } = defineProps<{ text: string }>();
</script>

<template>
  <Pressable :text="text" class="save" />
</template>
```

#svelte

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

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

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

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

<Pressable {text} class={["save", className]} {style} bind:ref {...attributes} />
```

#angular

<!-- prettier-ignore -->
```ts [save-action.ts]
import Pressable from "./pressable";
import {
  Component,
  Directive,
  ElementRef,
  type OnInit,
  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 };

@Component({
  selector: "uf-save-action",
  imports: [Pressable, ScopeAttributes],
  host: { "[attr.class]": "null", "[attr.style]": "'display: contents;'" },
  preserveWhitespaces: false,
  template: `
    @let text = this.text();
    <uf-pressable
      [text]="text"
      [class]="['save', this.class()].join(' ')"
      [style]="this.style()"
      [ufAttributes]="this.ufAttributes()"
      [ufListeners]="this.ufListeners()"
      [ufScope]="this.host"
      #ufElement
    />
  `,
})
export default class SaveAction {
  readonly text = input.required<string>();
  readonly class = input<string>();
  readonly style = input<Record<string, string | null | undefined>>();
  readonly ufAttributes = input<Record<string, unknown>>();
  readonly ufListeners = input<Listeners>();
  private readonly rootComponent = viewChild("ufElement", { read: Pressable });
  readonly ufElement = computed(() => this.rootComponent()?.ufElement());
  protected readonly host = inject<ElementRef<HTMLElement>>(ElementRef).nativeElement;
}
```

#solid

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

export default function SaveAction(
  props: { text: string } & Omit<ComponentProps<typeof Pressable>, "text">,
) {
  const [, others] = splitProps(props, ["text", "class"]);

  return (
    <Pressable text={props.text} class={props.class ? `save ${props.class}` : "save"} {...others} />
  );
}
```

#qwik

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

export default component$<
  { text: string } & Omit<PropsOf<typeof Pressable>, "text" | "class" | "style"> & {
      class?: ClassList;
      style?: CSSProperties;
    }
>(({ text, class: className, style, ...attributes }) => {
  return (
    <>
      <Pressable text={text} class={["save", className]} style={style} {...attributes} />
    </>
  );
});
```

#astro

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

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

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

<Pressable text={text} class:list={["save", className]} style={style} {...attrs} />
```

::

- React, Svelte, Qwik and Astro spread the props' rest on `Pressable`, after the class they merge. Svelte binds `bind:ref` on it too, so a ref passes on.
- React, Solid and Qwik type what passes on with the root component's own props, `ComponentPropsWithRef<typeof Pressable>`, `ComponentProps<typeof Pressable>` and `PropsOf<typeof Pressable>`, without the props `SaveAction` sets itself. So a root prop typed narrower than the attribute of its name, like `value: number`, still type-checks. On Qwik, a generic root component keeps its tag's attributes, since `PropsOf` can't infer its props.
- Vue passes it on by itself.
- Solid takes `text` and `class` out with `splitProps`, and spreads the others on `Pressable`.
- Angular passes both records on, `[ufAttributes]="this.ufAttributes()"`. Its `ufElement` is a `computed` of `Pressable`'s own, so a ref on `SaveAction` reaches the button.
- Qwik serialises a component's props, and a function isn't serialisable. So where the root component also carries the component's own template ref, Qwik passes it one signal, the parent's ref or else the own one, and a visible task fills the own one from the parent's.

A name the root component declares can't fall through to it. If `Pressable` emitted `click`, `onClick` on `SaveAction` would be [UF1002](/docs/reference/diagnostics#UF1002), and so would a prop or a model `Pressable` declares, since Vue would give it to that declaration and the other targets to the `<button>`. Pass it to `Pressable` directly, or declare it on `SaveAction`.

## Refs

A `ref` on a component that doesn't call `defineExpose` holds its root element, as Vue's `$el` does: through a chain of root components, and whatever `inheritAttrs` says. Type the ref 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. `Bio` turns fallthrough off and spreads no rest, and a ref on it still holds its root, so "Edit bio" focuses its `<input>`. A ref of another type, or on a component whose root isn't one element, is [UF3046](/docs/reference/diagnostics#UF3046).

A component that exposes functions gives a ref those alone, never its element. So a ref through a root component that exposes functions is UF3046 too: it would hold those functions, which the component you put the ref on doesn't expose, and no element. Expose a function from that component, or give it an element root. [Expose and component refs](/docs/components/expose-and-refs#a-ref-on-a-component-that-exposes-nothing) shows what each target writes for this case.

## Putting it on another element

Sometimes the root isn't the element a parent means. A text field's root is often a `<label>` around an `<input>`, and the `id`, the `placeholder` and the `focus` listener belong on the `<input>`. So a component can turn fallthrough to its root off with `defineOptions({ inheritAttrs: false })`, end its props pattern with a rest, `...rest`, and spread it whole on the element that should take it:

<!-- prettier-ignore -->
```tsx [Field.uf.tsx]
import { defineOptions } from "@uxfront/unframework";

// Turns fallthrough off and spreads what its consumer passes on its <input>, not on its root.
export default function Field({ label, ...rest }: { label: string }) {
  defineOptions({ inheritAttrs: false });
  return (
    <label class="field">
      {label} <input {...rest} name={label.toLowerCase()} />
    </label>
  );
}
```

<!-- prettier-ignore -->
```tsx [SignUp.uf.tsx]
import { ref } from "@uxfront/unframework";

import Field from "./Field.uf.tsx";

export default function SignUp() {
  const focuses = ref(0);
  return (
    <form aria-label="Sign up">
      <p id="email-hint">We never share it.</p>
      <Field
        label="Email"
        id="email"
        aria-describedby="email-hint"
        placeholder="you@example.com"
        class="wide"
        style="margin-top: 4px"
        onFocus={() => focuses.value++}
      />
      <p>Focuses: {focuses.value}</p>
    </form>
  );
}
```

`rest` holds exactly what would have fallen through to the root, its `class`, `style` and listeners included. So the `<input>` takes all of it, and the `<label>` keeps only its own class:

<!-- prettier-ignore -->
```html
<form aria-label="Sign up">
  <p id="email-hint">
    "We never share it."
  </p>
  <label class="field">
    "Email "
    <input aria-describedby="email-hint" class="wide" id="email" name="email" placeholder="you@example.com" style="margin-top: 4px;" uf:value="">
  </label>
  <p>
    "Focuses: 0"
  </p>
</form>
```

The parent checks what it passes against the `<input>`, or as SVG where the element is inside an `<svg>`, like a `<circle>`. The parent's value still wins over the element's own, wherever the spread sits. `rest` never holds a declared prop, and a styled parent's `data-uf-*` scope attribute stays on the root.

The rest has one canonical form, and one use. It needs `defineOptions({ inheritAttrs: false })`, or it is [UF2001](/docs/reference/diagnostics#UF2001), whose safe fix adds the call.

Its one use is a whole spread on one element outside any list. A member read like `rest.id`, a second spread, a spread in a list or a spread on a component is UF2001 too, since each target holds the rest its own way, and a member of it would mean something different on each. So is a spread inside a slot's fill, which the child may render many times, and a spread on `<component is>`, which chooses among several elements.

::framework-switcher

#react

<!-- prettier-ignore -->
```tsx [Field.tsx]
import type { ComponentPropsWithoutRef, Ref } from "react";

export type FieldAttributes = Omit<ComponentPropsWithoutRef<"input">, "label" | "children"> & {
  ref?: Ref<HTMLLabelElement>;
};

export default function Field({
  label,
  className,
  style,
  ref,
  ...attributes
}: { label: string } & FieldAttributes) {
  return (
    <label className="field" {...scopeAttributes(attributes)} ref={ref}>
      {label}{" "}
      <input
        name={label.toLowerCase()}
        className={className}
        style={style}
        {...restAttributes(attributes)}
      />
    </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 key of Object.keys(props)) {
    if (key.startsWith("data-uf-")) scope[key] = "";
  }
  return scope;
}

/** What the consumer passes, but the scope attributes of its styled parents, which the root keeps. */
function restAttributes<T extends object>(props: T): T {
  const rest = { ...props };
  for (const key of Object.keys(rest)) {
    if (key.startsWith("data-uf-")) Reflect.deleteProperty(rest, key);
  }
  return rest;
}
```

#vue

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

const { label } = defineProps<
  { label: string } & /* @vue-ignore */ (Omit<
    IntrinsicElementAttributes["input"],
    "label" | "autocomplete"
  > &
    Partial<Record<"autocomplete", string>>)
>();
defineOptions({ inheritAttrs: false });

/** The scope attributes of the styled parents that render this component, for its root. */
function scopeAttrs(attrs: Record<string, unknown>): Record<string, unknown> {
  return Object.fromEntries(Object.entries(attrs).filter(([name]) => name.startsWith("data-uf-")));
}

/** What the consumer passes, but the scope attributes its root keeps. */
function restAttrs(attrs: Record<string, unknown>): Record<string, unknown> {
  return Object.fromEntries(Object.entries(attrs).filter(([name]) => !name.startsWith("data-uf-")));
}
</script>

<template>
  <label
    class="field"
    v-bind="scopeAttrs($attrs)"
  >{{ label }} <input :name="label.toLowerCase()" v-bind="restAttrs($attrs)" /></label>
</template>
```

#svelte

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

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

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

  let { label, class: className, style, ref = $bindable(null), ...rest }: Props = $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;
  }

  /** What the consumer passes, but the scope attributes the root keeps. */
  function restAttributes(props: object): Record<string, unknown> {
    return Object.fromEntries(
      Object.entries(props).filter(([name]) => !name.startsWith("data-uf-")),
    );
  }
</script>

<label
  class="field"
  bind:this={ref}
  {...scopeAttributes(rest)}
>{label} <input name={label.toLowerCase()} class={className} {style} {...restAttributes(rest)} /></label>
```

#angular

<!-- prettier-ignore -->
```ts [field.ts]
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-field",
  imports: [ScopeAttributes, Fallthrough],
  host: { "[attr.class]": "null", "[attr.style]": "'display: contents;'" },
  preserveWhitespaces: false,
  template: `
    @let label = this.label();
    <label
      class="field"
      [ufScope]="this.host"
      #ufElement
    >{{ label }}&ngsp;<input
      [ufFallthrough]="{ attributes: this.ufAttributes(), listeners: this.ufListeners() }"
      [attr.name]="'name' in (this.ufAttributes() ?? {}) ? this.ufAttributes()?.['name'] : label.toLowerCase()"
      [class]="this.class()"
      [style]="this.style()"
    /></label>
  `,
})
export default class Field {
  readonly label = input.required<string>();
  readonly class = input<string>();
  readonly style = input<Record<string, string | null | undefined>>();
  readonly ufAttributes = input<Record<string, unknown>>();
  readonly ufListeners = input<Listeners>();
  readonly ufElement = viewChild<ElementRef<HTMLLabelElement>>("ufElement");
  protected readonly host = inject<ElementRef<HTMLElement>>(ElementRef).nativeElement;
}
```

#solid

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

export default function Field(
  props: { label: string } & Omit<ComponentProps<"input">, "label" | "style" | "ref"> & {
      style?: JSX.CSSProperties;
    } & Pick<ComponentProps<"label">, "ref">,
) {
  const [, rest] = splitProps(props, ["label", "ref"]);

  return (
    <label class="field" {...scopeAttributes(props)} ref={props.ref}>
      {props.label} <input name={props.label.toLowerCase()} {...restAttributes(rest)} />
    </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;
}

/** What the consumer passes, but the scope attributes of the styled parents, which the root keeps. */
function restAttributes(rest: object): Record<string, unknown> {
  const attributes: Record<string, unknown> = {};
  for (const [name, value] of Object.entries(rest)) {
    if (!name.startsWith("data-uf-")) attributes[name] = value;
  }
  return attributes;
}
```

#qwik

<!-- prettier-ignore -->
```tsx [Field.tsx]
import {
  type CSSProperties,
  type ClassList,
  type PropsOf,
  type Signal,
  component$,
} 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, ref, ...attributes }) => {
  return (
    <label class="field" {...scopeAttributes(attributes)} ref={ref}>
      {label}{" "}
      <input
        name={label.toLowerCase()}
        class={className}
        style={style}
        {...restAttributes(attributes)}
      />
    </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 key of Object.keys(props)) {
    if (key.startsWith("data-uf-")) scope[key] = "";
  }
  return scope;
}

/** What the consumer passes, but the scope attributes its root keeps. */
function restAttributes(attributes: PropsOf<"input">): PropsOf<"input"> {
  return Object.fromEntries(
    Object.entries(attributes).filter(([key]) => !key.startsWith("data-uf-")),
  );
}
```

#astro

<!-- prettier-ignore -->
```astro [Field.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, ...attrs } = 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;
}

/** What the consumer passes, but its styled parents' scope attributes, which the root keeps. */
function withoutScope(rest: object): Record<string, unknown> {
  return Object.fromEntries(Object.entries(rest).filter(([key]) => !key.startsWith("data-uf-")));
}
---

<label
  class="field"
  {...scopeAttributes(Astro.props)}
>{label} <input
  {...withoutScope(attrs)}
  name={"name" in Astro.props ? name : label.toLowerCase()}
  class:list={[className]}
  style={style}
/></label>
```

::

- React, Svelte, Solid and Qwik spread the rest on the `<input>` through an inline helper, `restAttributes`, which leaves out the styled parents' scope attributes, and the `<label>` keeps those through `scopeAttributes`. The `<label>` also takes the parent's `ref`, since a ref holds the root element.
- Vue binds `restAttrs($attrs)` on the `<input>` and `scopeAttrs($attrs)` on the `<label>`. Its props type declares the input's attributes behind `/* @vue-ignore */`, since vue-tsc reads them only from a root or a bare `$attrs`.
- Angular binds `[ufFallthrough]` on the `<input>`, beside the `class` and `style` inputs, and `ufElement` stays the `<label>`.
- Astro spreads `withoutScope(attrs)` on the `<input>`, and gives the input its own `name` only where the parent passes none, `"name" in Astro.props ? name : label.toLowerCase()`.

## Turning it off

`defineOptions({ inheritAttrs: false })` without a rest makes a component take nothing it doesn't declare, so its root keeps a layout of its own:

<!-- prettier-ignore -->
```tsx [Field.uf.tsx]
import { defineOptions } from "@uxfront/unframework";

// Renders no class or style a consumer passes: its own layout is fixed.
export default function Field({ label }: { label: string }) {
  defineOptions({ inheritAttrs: false });
  return (
    <label class="field">
      {label} <input name={label.toLowerCase()} />
    </label>
  );
}
```

Vue writes the same `defineOptions`. The other targets type and spread nothing that falls through, and Angular's host still clears `class` and `style`. The argument is that object literal and nothing else ([UF2031](/docs/reference/diagnostics#UF2031)).

## A `<component is>` root

A component whose root is a [`<component is>` over tags](/docs/components/dynamic-components#as-a-components-root) takes what a parent passes as a one-element root does, on whichever tag renders: `class` and `style`, the attributes every tag takes, the DOM listeners and a ref. So does a component whose root component renders one. Here `Base` renders a link with an `href` and a button without one, and `Primary` renders `Base`:

<!-- prettier-ignore -->
```tsx [Base.uf.tsx]
// Its root is a `<component is>` over tags: a link with an `href`, and a button without one. It
// declares no `id`, ARIA, `data-*` or `title`, no listener and exposes nothing, so a consumer's
// attributes, listeners and ref fall through to whichever tag renders (ADR-0122). Its own `title`
// gives way to a consumer's, and its own click listener runs before a consumer's.
export default function Base({
  href,
  disabled,
  text,
}: {
  href?: string;
  disabled?: boolean;
  text: string;
}) {
  // A consumer handles a click, as a router would: the link does not navigate.
  function press(event: MouseEvent) {
    event.preventDefault();
  }
  return (
    <component
      is={href ? "a" : "button"}
      href={href}
      disabled={disabled}
      class="base"
      title="Base"
      onClick={press}
    >
      {text}
    </component>
  );
}
```

<!-- prettier-ignore -->
```tsx [Primary.uf.tsx]
import Base from "./Base.uf.tsx";

// Its root is a component: what falls through to it passes on to whichever tag Base renders.
export default function Primary({ href, text }: { href?: string; text: string }) {
  return <Base href={href} text={text} class="primary" />;
}
```

The page passes each an `id`, an ARIA and a `data-*` attribute, listeners and a ref, and a button toggles both between a link and a button:

<!-- prettier-ignore -->
```tsx [Page.uf.tsx]
import { ref, useTemplateRef } from "@uxfront/unframework";

import Base from "./Base.uf.tsx";
import Primary from "./Primary.uf.tsx";

export default function Page() {
  const linked = ref(true);
  const log = ref<string[]>([]);
  const direct = useTemplateRef<HTMLAnchorElement | HTMLButtonElement>();
  const chained = useTemplateRef<HTMLAnchorElement | HTMLButtonElement>();

  function record(line: string) {
    log.value = [...log.value, line];
  }

  return (
    <section aria-label="Page">
      <Base
        href={linked.value ? "#direct" : undefined}
        text="Direct"
        id="direct"
        aria-label="Direct"
        data-testid="direct"
        title="Go"
        onClick={(event) => record(`click on ${(event.currentTarget as Element).localName}`)}
        onKeydown={(event) =>
          record(`keydown ${event.key} on ${(event.currentTarget as Element).localName}`)
        }
        ref={direct}
      />
      <Primary
        href={linked.value ? "#chained" : undefined}
        text="Chained"
        id="chained"
        aria-label="Chained"
        data-testid="chained"
        onClick={(event) => record(`chained on ${(event.currentTarget as Element).localName}`)}
        ref={chained}
      />
      <button type="button" onClick={() => (linked.value = !linked.value)}>
        Toggle
      </button>
      <button type="button" onClick={() => direct.value?.focus()}>
        Focus direct
      </button>
      <button type="button" onClick={() => chained.value?.focus()}>
        Focus chained
      </button>
      <ol aria-label="Log">
        {log.value.map((entry, index) => (
          <li key={index}>{entry}</li>
        ))}
      </ol>
    </section>
  );
}
```

Each attribute lands on the link, then on the button once the toggle runs, and the page's `title` wins over `Base`'s own. Each listener logs the element it runs on, `a` or `button`, after `Base`'s own click listener, and each ref focuses the element that renders, before and after the toggle.

What falls through reaches the child whole, and the child chooses its tag as it renders, so an attribute falls through only where every tag takes it: `id`, `title`, `tabindex`, `aria-*` and `data-*`, with `type` on a link or a button. One that only some tags take, like `disabled`, which `<a>` doesn't take, is [UF1002](/docs/reference/diagnostics#UF1002): declare it as a prop and set it on the `<component is>`, which renders it only on the tags that take it. One that no tag takes is [UF3035](/docs/reference/diagnostics#UF3035).

A ref holds the element that renders, so type it as the union of the tags' DOM interfaces, in any order: `useTemplateRef<HTMLAnchorElement | HTMLButtonElement>()`. Tags that share an interface, like `h2` and `h3`, give it once, `HTMLHeadingElement`. A ref typed as one tag's interface, or as a supertype such as `HTMLElement`, is [UF3046](/docs/reference/diagnostics#UF3046).

Each target puts what falls through on the tag that renders, and types it as what every tag takes:

::framework-switcher

#react

<!-- prettier-ignore -->
```tsx [Base.tsx]
import {
  type ComponentPropsWithoutRef,
  type DOMAttributes,
  type MouseEvent,
  type Ref,
  type RefCallback,
  useMemo,
} from "react";

export type BaseAttributes = Omit<
  ComponentPropsWithoutRef<"a"> & ComponentPropsWithoutRef<"button">,
  | "href"
  | "disabled"
  | "text"
  | "children"
  | keyof DOMAttributes<HTMLAnchorElement | HTMLButtonElement>
> &
  Omit<
    DOMAttributes<HTMLAnchorElement | HTMLButtonElement>,
    "children" | "dangerouslySetInnerHTML"
  > & { ref?: Ref<HTMLAnchorElement | HTMLButtonElement> };

function press(event: MouseEvent) {
  event.preventDefault();
}

export default function Base({
  href,
  disabled,
  text,
  className,
  style,
  onClick,
  ref,
  ...attributes
}: { href?: string; disabled?: boolean; text: string } & BaseAttributes) {
  const rootRef = useMemo(() => mergeRefs(ref), [ref]);

  const Tag = href ? "a" : "button";

  return (
    <Tag
      href={Tag === "a" ? href : undefined}
      disabled={Tag === "button" ? disabled : undefined}
      className={cx("base", className)}
      title="Base"
      onClick={(event) => {
        press(event);
        onClick?.(event);
      }}
      style={style}
      ref={rootRef}
      {...attributes}
    >
      {text}
    </Tag>
  );
}

/** 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(" ");
}

/** 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();
    };
  };
}
```

#vue

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

const {
  href = undefined,
  disabled = undefined,
  text,
} = defineProps<
  { href?: string; disabled?: boolean; text: string } & /* @vue-ignore */ Omit<
    IntrinsicElementAttributes["a"] & IntrinsicElementAttributes["button"],
    "href" | "disabled" | "text"
  >
>();

function press(event: MouseEvent) {
  event.preventDefault();
}
</script>

<template>
  <component
    :is="href ? 'a' : 'button'"
    :href="(href ? 'a' : 'button') === 'a' ? href : undefined"
    :disabled="(href ? 'a' : 'button') === 'button' ? disabled : undefined"
    class="base"
    title="Base"
    @click="press"
  >{{ text }}</component>
</template>
```

#svelte

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

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

  type Props = Omit<
    HTMLAnchorAttributes & HTMLButtonAttributes,
    | "href"
    | "disabled"
    | "text"
    | "children"
    | "class"
    | "style"
    | "ref"
    | keyof DOMAttributes<HTMLElementTagNameMap["a" | "button"]>
  > &
    Omit<DOMAttributes<HTMLElementTagNameMap["a" | "button"]>, "children"> & {
      href?: string;
      disabled?: boolean;
      text: string;
      class?: ClassValue;
      style?: string;
      ref?: HTMLElementTagNameMap["a" | "button"] | null;
    };

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

  function press(event: MouseEvent) {
    event.preventDefault();
  }
</script>

<svelte:element
  this={href ? "a" : "button"}
  href={(href ? "a" : "button") === "a" ? href : undefined}
  disabled={(href ? "a" : "button") === "button" ? disabled : undefined}
  class={["base", className]}
  title="Base"
  onclick={((event) => {
    press(event);
    onclick?.(event);
  }) satisfies Props["onclick"]}
  {style}
  bind:this={ref}
  {...attributes}
>{text}</svelte:element>
```

#angular

<!-- prettier-ignore -->
```ts [base.ts]
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-base",
  imports: [ScopeAttributes, Fallthrough],
  host: { "[attr.class]": "null", "[attr.style]": "'display: contents;'" },
  preserveWhitespaces: false,
  template: `
    @let href = this.href();
    @let disabled = this.disabled();
    @let text = this.text();
    @switch (href ? "a" : "button") {
      @case ("a") {
        <a
          [attr.href]="'href' in (this.ufAttributes() ?? {}) ? this.ufAttributes()?.['href'] : href"
          class="base"
          title="Base"
          (click)="press($event)"
          [class]="this.class()"
          [style]="this.style()"
          [ufFallthrough]="{ attributes: this.ufAttributes(), listeners: this.ufListeners() }"
          [ufScope]="this.host"
          #ufElement
        >{{ text }}</a>
      } @case ("button") {
        <button
          [attr.disabled]="'disabled' in (this.ufAttributes() ?? {}) ? this.ufAttributes()?.['disabled'] : disabled ? '' : null"
          class="base"
          title="Base"
          (click)="press($event)"
          [class]="this.class()"
          [style]="this.style()"
          [ufFallthrough]="{ attributes: this.ufAttributes(), listeners: this.ufListeners() }"
          [ufScope]="this.host"
          #ufElement
        >{{ text }}</button>
      }
    }
  `,
})
export default class Base {
  readonly href = input<string>();
  readonly disabled = input<boolean>();
  readonly text = input.required<string>();
  readonly class = input<string>();
  readonly style = input<Record<string, string | null | undefined>>();
  readonly ufAttributes = input<Record<string, unknown>>();
  readonly ufListeners = input<Listeners>();
  readonly ufElement = viewChild<ElementRef<HTMLAnchorElement | HTMLButtonElement>>("ufElement");

  protected press(event: MouseEvent) {
    event.preventDefault();
  }
  protected readonly host = inject<ElementRef<HTMLElement>>(ElementRef).nativeElement;
}
```

#solid

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

function press(event: MouseEvent) {
  event.preventDefault();
}

export default function Base(
  props: { href?: string; disabled?: boolean; text: string } & Omit<
    Omit<
      ComponentProps<"a"> & ComponentProps<"button">,
      keyof JSX.DOMAttributes<HTMLElementTagNameMap["a" | "button"]>
    > &
      JSX.DOMAttributes<HTMLElementTagNameMap["a" | "button"]>,
    "href" | "disabled" | "text" | "style" | "onClick"
  > & {
      style?: JSX.CSSProperties;
      onClick?: Extract<
        (Omit<
          ComponentProps<"a"> & ComponentProps<"button">,
          keyof JSX.DOMAttributes<HTMLElementTagNameMap["a" | "button"]>
        > &
          JSX.DOMAttributes<HTMLElementTagNameMap["a" | "button"]>)["onClick"],
        (event: never) => void
      >;
    },
) {
  const [, others] = splitProps(props, ["href", "disabled", "text", "ref", "class", "onClick"]);

  return (
    <Dynamic
      component={props.href ? "a" : "button"}
      href={(props.href ? "a" : "button") === "a" ? props.href : undefined}
      disabled={(props.href ? "a" : "button") === "button" ? props.disabled : undefined}
      class={props.class ? `base ${props.class}` : "base"}
      title="Base"
      onClick={
        ((event) => {
          press(event);
          props.onClick?.(event);
        }) satisfies typeof props.onClick
      }
      ref={(element: HTMLElementTagNameMap["a" | "button"]) => {
        if (typeof props.ref === "function") props.ref(element);
      }}
      {...others}
    >
      {props.text}
    </Dynamic>
  );
}
```

#qwik

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

export default component$<
  { href?: string; disabled?: boolean; text: string } & Omit<
    PropsOf<"a"> & PropsOf<"button">,
    "href" | "disabled" | "text" | "class" | "style"
  > & { class?: ClassList; style?: CSSProperties }
>(({ href, disabled, text, class: className, style, onClick$, ...attributes }) => {
  const Tag = href ? "a" : "button";

  return (
    <>
      {Tag === "a" ? (
        <a
          href={href}
          class={["base", className]}
          title="Base"
          preventdefault:click
          onClick$={[
            sync$((event: MouseEvent) => {
              event.preventDefault();
            }),
            onClick$,
          ]}
          style={style}
          {...attributes}
        >
          {text}
        </a>
      ) : (
        <button
          disabled={disabled}
          class={["base", className]}
          title="Base"
          preventdefault:click
          onClick$={[
            sync$((event: MouseEvent) => {
              event.preventDefault();
            }),
            onClick$,
          ]}
          style={style}
          {...attributes}
        >
          {text}
        </button>
      )}
    </>
  );
});
```

#astro

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

interface Props extends Omit<
  HTMLAttributes<"a"> & HTMLAttributes<"button">,
  "href" | "disabled" | "text"
> {
  href?: string;
  disabled?: boolean;
  text: string;
  class?: string;
  style?: Record<string, string | number | undefined>;
}

const { href, disabled, text, class: className, style, title, ...attrs } = Astro.props;

const Tag = href ? "a" : "button";
---

<Tag
  href={Tag === "a" ? href : undefined}
  disabled={Tag === "button" ? disabled : undefined}
  class:list={["base", className]}
  title={"title" in Astro.props ? title : "Base"}
  style={style}
  {...attrs}
>{text}</Tag>
```

::

Angular writes each tag in an `@case` of its own, and each tag's element binds the `Fallthrough` directive and holds the `ufElement` ref. Qwik writes a `<component is>` with listeners of its own as one element per tag, and each takes the rest. React and Solid hand the ref to whichever tag renders through a callback, since each tag types its `ref` for itself. Astro renders on the server only, so a listener that falls through is dropped, with [UF4001](/docs/reference/diagnostics#UF4001) for information.

## Where nothing can fall through

A parent that passes a component something it doesn't declare has it rejected rather than dropped ([UF3045](/docs/reference/diagnostics#UF3045)) where the component has no element to take it: it turns fallthrough off and spreads no rest, or its root is a fragment, a conditional or a list, a `<component is>` whose `is` reads a setup value, whose tags the parent can't read, or a root component that takes nothing itself. Pass what the child declares, spread its props' rest on one of its elements, or give it one root element.

A [`<component is>`](/docs/components/dynamic-components) whose candidates are components passes them `class` and `style` only. Anything else that would fall through to a candidate is [UF1002](/docs/reference/diagnostics#UF1002), so pass what every candidate declares, or render each by its own tag.

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