# Fallthrough

> A parent's class and style on a component fall through to its root element, merged with the root's own. defineOptions({ inheritAttrs: false }) turns it off.

A parent often needs to place or tweak a child it doesn't own: give a tag some margin, mark the picked one, widen a button. So a parent's `class` and `style` on a component fall through to the component's root element, merged with the root's own. They're the only attributes that do: every other attribute is a prop the child declares, so the child's API stays the whole story of what it accepts.

## Class and style

A component with one root element takes `class` and `style` without declaring them. 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>
  );
}
```

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 { CSSProperties } from "react";

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

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 }}
      {...scopeAttributes(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(" ");
}

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

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

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

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} {...scopeAttributes(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(" ");
}

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

#vue

<!-- prettier-ignore -->
```vue [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 } from "svelte/elements";

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

  let { label, class: className, style, ...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("; ");
  }

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

<span
  class={["tag", className]}
  style={mergeStyle({ padding: "2px 6px", color: "rgb(30, 30, 30)" }, style)}
  {...scopeAttributes(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 } from "svelte/elements";

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

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

  let active = $state(false);

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

<div class={["tags", className]} {style} {...scopeAttributes(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 {
  Component,
  Directive,
  ElementRef,
  type OnInit,
  Renderer2,
  inject,
  input,
} from "@angular/core";

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

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

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

@Component({
  selector: "uf-tag",
  imports: [ScopeAttributes],
  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()"
      [ufScope]="this.host"
    >{{ label }}</span>
  `,
})
export default class Tag {
  readonly label = input.required<string>();
  readonly class = input<string>();
  readonly style = input<Record<string, string | null | undefined>>();
  protected readonly host = inject<ElementRef<HTMLElement>>(ElementRef).nativeElement;
}
```

<!-- prettier-ignore -->
```ts [tags.ts]
import Tag from "./tag";
import {
  Component,
  Directive,
  ElementRef,
  type OnInit,
  Renderer2,
  inject,
  input,
  signal,
} from "@angular/core";

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

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

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

@Component({
  selector: "uf-tags",
  imports: [Tag, ScopeAttributes],
  host: { "[attr.class]": "null", "[attr.style]": "'display: contents;'" },
  preserveWhitespaces: false,
  template: `
    @let active = this.active();
    <div class="tags" [class]="this.class()" [style]="this.style()" [ufScope]="this.host">
      <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>>();
  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 { JSX } from "solid-js";

export default function Tag(
  props: { label: string } & { class?: string; style?: JSX.CSSProperties },
) {
  return (
    <span
      class={props.class ? `tag ${props.class}` : "tag"}
      style={{ ...{ padding: "2px 6px", color: "rgb(30, 30, 30)" }, ...props.style }}
      {...scopeAttributes(props)}
    >
      {props.label}
    </span>
  );
}

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

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

export default function Tags(props: { class?: string; style?: JSX.CSSProperties }) {
  const [active, setActive] = createSignal(false);

  return (
    <div
      class={props.class ? `tags ${props.class}` : "tags"}
      style={props.style}
      {...scopeAttributes(props)}
    >
      <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(" ");
}

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

#qwik

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

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

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

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

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

    return (
      <div class={["tags", className]} {...scopeAttributes(attributes)} style={style}>
        <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>
    );
  },
);

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

#astro

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

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

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

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

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

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

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

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

const active = false as boolean;
---

<div class:list={["tags", className]} style={style} {...scopeAttributes(Astro.props)}>
  <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 declare `className` or `class`, and `style`, beside the props, and merge them 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 element, and clears them from its host element, which keeps only `display: contents` (`fallthrough`, emulated). A parent binds them, `[class]="'wide'"`, so they reach the inputs.

So every output but Vue's declares the two on each component with one root element, and you'll see them on every page of these docs, even where no parent passes them.

React, Solid, Svelte, Qwik and Astro outputs also spread `scopeAttributes(…)` on the root, with a small helper of that name after the component, in Svelte's script or in Astro's frontmatter. That carries a styled parent's `data-uf-*` scope attribute to the child's root, so the parent's stylesheet reaches it ([`child-root-scope`](/docs/reference/targets#capabilities), emulated). It passes on no other attribute. Angular's root binds `[ufScope]="this.host"` instead, a small directive declared before the component, which moves that attribute from the host element onto the root.

## Through a component root

A component whose root is another component passes the parent's `class` and `style` on to that component's root:

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

// Its root is a component: a class passed to it passes on to that component's root.
export default function Primary({ text }: { text: string }) {
  return <Base text={text} class="primary" />;
}
```

`<Primary text="Save" class="wide" />` renders `<button class="base primary wide">`: `Base` merges `primary` and `wide` into its own `base`.

## Turning it off

`defineOptions({ inheritAttrs: false })` makes a component take neither, 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 leave out the `class` and `style` props, and Angular's host still clears both. The argument is that object literal and nothing else ([UF2031](/docs/reference/diagnostics#UF2031)).

A parent that passes `class` or `style` to such a component has them rejected rather than dropped ([UF3045](/docs/reference/diagnostics#UF3045)), and so does one that passes them to a component whose root is a fragment, a conditional or a list, which has no one root to take them. Style an element around the component instead, or give the child a prop for its class.

## Only class and style

No other attribute falls through. An `id`, an `aria-*` or a `data-*` that the child doesn't declare is [UF3035](/docs/reference/diagnostics#UF3035), with a fix to the closest prop, and a listener the child doesn't declare is [UF3036](/docs/reference/diagnostics#UF3036). A design system that lets its users set them declares them as props. A rest element in the props, `{ label, ...rest }`, is [UF2001](/docs/reference/diagnostics#UF2001): fallthrough has one channel, and it is `class` and `style`.

Angular has no attribute spread, and a typed parent already rejects an attribute its child doesn't declare, which is why Unframework keeps fallthrough to these two on every target rather than Vue's every attribute.

The decisions behind this page are [ADR-0054](https://github.com/uxfront-com/unframework/blob/main/docs/adrs/0054-composition-on-every-target.md) and [ADR-0056](https://github.com/uxfront-com/unframework/blob/main/docs/adrs/0056-angular-hosts-in-composition.md).
