# Dynamic components

> <component is> renders one of a set of tags or components the compiler knows, chosen by a condition or a prop. Each framework gets its own dynamic element.

Sometimes the element itself depends on the data: a heading whose level follows its depth in an outline, a section title that drops a level when it is nested, a card that collapses into a chip. `<component is>` renders one of a set of tags, or one of a set of components, chosen by a condition or by a prop.

## Choosing a tag

`is` takes a conditional whose branches are tag names. The children apply to whichever tag renders, and each attribute to the tags that take it:

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

export default function Section({ title }: { title: string }) {
  const nested = ref(false);
  return (
    <article>
      <component is={nested.value ? "h3" : "h2"} class="title">
        {title}
      </component>
      <button type="button" onClick={() => (nested.value = !nested.value)}>
        {nested.value ? "Lift" : "Nest"}
      </button>
    </article>
  );
}
```

::framework-switcher

#react

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

export type SectionAttributes = Omit<ComponentPropsWithRef<"article">, "title" | "children">;

export default function Section({
  title,
  className,
  style,
  ...attributes
}: { title: string } & SectionAttributes) {
  const [nested, setNested] = useState(false);
  const nestedRef = useRef(nested);
  const Tag = nested ? "h3" : "h2";

  return (
    <article className={className} style={style} {...attributes}>
      <Tag className="title">{title}</Tag>
      <button
        type="button"
        onClick={() => {
          nestedRef.current = !nestedRef.current;
          setNested(nestedRef.current);
        }}
      >
        {nested ? "Lift" : "Nest"}
      </button>
    </article>
  );
}
```

#vue

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

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

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

<template>
  <article>
    <component :is="nested ? 'h3' : 'h2'" class="title">{{ title }}</component>
    <button type="button" @click="nested = !nested">{{ nested ? "Lift" : "Nest" }}</button>
  </article>
</template>
```

#svelte

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

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

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

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

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

<article class={className} {style} bind:this={ref} {...attributes}>
  <svelte:element this={nested ? "h3" : "h2"} class="title">{title}</svelte:element
  ><button type="button" onclick={() => (nested = !nested)}>{nested ? "Lift" : "Nest"}</button>
</article>
```

#angular

<!-- prettier-ignore -->
```ts [section.ts]
import { Fallthrough } from "./_unframework/Fallthrough";
import type { Listeners } from "./_unframework/Listeners";
import { ScopeAttributes } from "./_unframework/ScopeAttributes";
import { Component, ElementRef, inject, input, signal, viewChild } from "@angular/core";

@Component({
  selector: "uf-section",
  imports: [ScopeAttributes, Fallthrough],
  host: { "[attr.class]": "null", "[attr.style]": "'display: contents;'" },
  preserveWhitespaces: false,
  template: `
    @let title = this.title();
    @let nested = this.nested();
    <article
      [class]="this.class()"
      [style]="this.style()"
      [ufFallthrough]="{ attributes: this.ufAttributes(), listeners: this.ufListeners() }"
      [ufScope]="this.host"
      #ufElement
    >
      @switch (nested ? "h3" : "h2") {
        @case ("h3") {
          <h3 class="title">{{ title }}</h3>
        } @case ("h2") {
          <h2 class="title">{{ title }}</h2>
        }
      }
      <button type="button" (click)="onClick()">{{ nested ? "Lift" : "Nest" }}</button>
    </article>
  `,
})
export default class Section {
  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<HTMLElement>>("ufElement");
  protected readonly nested = signal(false);

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

#solid

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

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

  const [nested, setNested] = createSignal(false);

  return (
    <article {...others}>
      <Dynamic component={nested() ? "h3" : "h2"} class="title">
        {props.title}
      </Dynamic>
      <button type="button" onClick={() => setNested(!nested())}>
        {nested() ? "Lift" : "Nest"}
      </button>
    </article>
  );
}
```

#qwik

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

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

  const Tag = nested.value ? "h3" : "h2";

  return (
    <article class={className} style={style} {...attributes}>
      <>
        <Tag class="title">{title}</Tag>
      </>
      <button type="button" onClick$={() => (nested.value = !nested.value)}>
        {nested.value ? "Lift" : "Nest"}
      </button>
    </article>
  );
});
```

#astro

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

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

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

const nested = false as boolean;

const Tag = nested ? "h3" : "h2";
---

<article class:list={[className]} style={style} {...attrs}>
  <Tag class="title">{title}</Tag>
  <button type="button">{nested ? "Lift" : "Nest"}</button>
</article>
```

::

- React, Qwik and Astro hold the chosen tag in a constant, `const Tag = nested ? "h3" : "h2"`, and render `<Tag>`.
- Vue writes `<component :is>`, Svelte `<svelte:element this={…}>`, and Solid `<Dynamic component={…}>`.
- A strict Angular template can't choose an element by value, so Angular writes an `@switch` with one `@case` per tag, each with the attributes and children ([`dynamic-component`](/docs/reference/targets#capabilities), emulated).

An attribute that only some of the tags take, like `href`, which only `<a>` takes, renders only on those ([As a component's root](#as-a-components-root) shows it). One that no tag takes is [UF3006](/docs/reference/diagnostics#UF3006).

A prop typed as a union of tag names can choose the tag too, as a heading's level:

<!-- prettier-ignore -->
```tsx [Heading.uf.tsx]
export default function Heading({ tag, text }: { tag: "h1" | "h2" | "h3"; text: string }) {
  return (
    <component is={tag} class="heading">
      {text}
    </component>
  );
}
```

## As a component's root

A `<component is>` over tags can be a component's root. It renders one element, so it takes a parent's `class` and `style` as a one-element root does ([Fallthrough](/docs/components/fallthrough)), merged into whichever tag renders, and so does the styled parent's scope attribute. This button renders a link when it has an `href`:

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

// Its root is a `<component is>` over tags: a link with an `href`, and a button without one.
// `href` renders only on the link and `disabled` only on the button (ADR-0119).
export default function Base({
  href,
  disabled,
  text,
}: {
  href?: string;
  disabled?: boolean;
  text: string;
}) {
  const emit = defineEmits<{ press: [] }>();
  // The page handles a press, as a router would: the link does not navigate.
  function press(event: MouseEvent) {
    event.preventDefault();
    emit("press");
  }
  return (
    <component
      is={href ? "a" : "button"}
      href={href}
      disabled={disabled}
      class="base"
      style="padding: 4px 8px"
      onClick={press}
    >
      {text}
    </component>
  );
}
```

`href` renders only on the link, and `disabled` only on the button. An attribute that at least one tag takes is accepted, and renders only when a tag that takes it renders. One that no tag takes is still [UF3006](/docs/reference/diagnostics#UF3006), reported once, naming every tag. A spread's keys go on every tag, so every tag must take them.

A parent's other attributes, its DOM listeners and its ref fall through to whichever tag renders too, where every tag takes them: [A `<component is>` root](/docs/components/fallthrough#a-component-is-root) shows them.

::framework-switcher

#react

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

export interface BaseEvents {
  onPress?: () => void;
}

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

export default function Base({
  href,
  disabled,
  text,
  onPress,
  className,
  style,
  onClick,
  ref,
  ...attributes
}: { href?: string; disabled?: boolean; text: string } & BaseEvents & BaseAttributes) {
  function press(event: MouseEvent) {
    event.preventDefault();
    onPress?.();
  }

  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)}
      style={{ padding: "4px 8px", ...style }}
      onClick={(event) => {
        press(event);
        onClick?.(event);
      }}
      ref={rootRef}
      {...attributes}
    >
      {text}
    </Tag>
  );
}
```

#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" | "onPress"
  >
>();
const emit = defineEmits<{ press: [] }>();

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

<template>
  <component
    :is="href ? 'a' : 'button'"
    :href="(href ? 'a' : 'button') === 'a' ? href : undefined"
    :disabled="(href ? 'a' : 'button') === 'button' ? disabled : undefined"
    class="base"
    style="padding: 4px 8px"
    @click="press"
  >{{ text }}</component>
</template>
```

#svelte

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

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

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

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

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

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

#angular

<!-- prettier-ignore -->
```ts [base.ts]
import { Fallthrough } from "./_unframework/Fallthrough";
import type { Listeners } from "./_unframework/Listeners";
import { ScopeAttributes } from "./_unframework/ScopeAttributes";
import { Component, ElementRef, inject, input, output, viewChild } from "@angular/core";

@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"
          [style]="{ padding: '4px 8px', ...this.style() }"
          (click)="onPress($event)"
          [class]="this.class()"
          [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"
          [style]="{ padding: '4px 8px', ...this.style() }"
          (click)="onPress($event)"
          [class]="this.class()"
          [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 press = output<void>();
  readonly ufElement = viewChild<ElementRef<HTMLAnchorElement | HTMLButtonElement>>("ufElement");

  protected onPress(event: MouseEvent) {
    event.preventDefault();
    this.press.emit();
  }
  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";

export interface BaseEvents {
  onPress?: () => void;
}

export default function Base(
  props: { href?: string; disabled?: boolean; text: string } & BaseEvents &
    Omit<
      Omit<
        ComponentProps<"a"> & ComponentProps<"button">,
        keyof JSX.DOMAttributes<HTMLElementTagNameMap["a" | "button"]>
      > &
        JSX.DOMAttributes<HTMLElementTagNameMap["a" | "button"]>,
      "href" | "disabled" | "text" | "onPress" | "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",
    "onPress",
    "ref",
    "class",
    "style",
    "onClick",
  ]);

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

  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"}
      style={{ ...{ padding: "4px 8px" }, ...props.style }}
      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,
  type QRL,
  component$,
} from "@qwik.dev/core";

export interface BaseEvents {
  onPress$?: QRL<() => void>;
}

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

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

  return (
    <>
      {Tag === "a" ? (
        <a
          href={href}
          class={["base", className]}
          style={{ padding: "4px 8px", ...style }}
          preventdefault:click
          onClick$={[press, onClick$]}
          {...attributes}
        >
          {text}
        </a>
      ) : (
        <button
          disabled={disabled}
          class={["base", className]}
          style={{ padding: "4px 8px", ...style }}
          preventdefault:click
          onClick$={[press, onClick$]}
          {...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, ...attrs } = Astro.props;

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

<Tag
  href={Tag === "a" ? href : undefined}
  disabled={Tag === "button" ? disabled : undefined}
  class:list={["base", className]}
  style={{ padding: "4px 8px", ...style }}
  {...attrs}
>{text}</Tag>
```

::

- React, Qwik and Astro guard an attribute on the constant, `href={Tag === "a" ? href : undefined}`, and Vue, Svelte and Solid on `is` itself. Each framework leaves out an attribute whose value is `undefined`.
- Angular writes each `@case` with only the attributes its tag takes, and merges the `class` and `style` inputs into each one.
- Qwik writes one element per tag where the `<component is>` has listeners, and merges the `class` and `style` into each.

A parent passes `class` and `style` as to any component, here through `Primary`, whose root is `Base`:

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

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

// Its root is a component: a class passed to it passes on to whichever tag that component renders.
export default function Primary({
  href,
  disabled,
  text,
}: {
  href?: string;
  disabled?: boolean;
  text: string;
}) {
  const emit = defineEmits<{ press: [] }>();
  return (
    <Base
      href={href}
      disabled={disabled}
      text={text}
      class="primary"
      onPress={() => emit("press")}
    />
  );
}
```

The parent reads the tags from `is` when it is a literal, a conditional of literals or a prop typed as a union of tags. An `is` that reads a setup value, such as `tag.value`, gives the parent no tags to read, so a `class` passed to it is [UF3045](/docs/reference/diagnostics#UF3045).

## Choosing a component

The candidates can be components instead, imported or of the same module. Each one must declare every prop, model and slot you pass:

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

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

export default function Tag({ label }: { label: string }) {
  const compact = ref(true);
  return (
    <section aria-label="Tag">
      <component is={compact.value ? Chip : Card} label={label} />
      <button type="button" onClick={() => (compact.value = !compact.value)}>
        {compact.value ? "Expand" : "Compact"}
      </button>
    </section>
  );
}
```

React, Qwik and Astro hold the chosen component in a constant, Vue writes `<component :is="compact ? Chip : Card">`, Svelte a `$derived` component, Solid `<Dynamic>`, and Angular an `@switch` with a `@case` per component. A prop or a fill that one of the candidates doesn't declare is [UF3035](/docs/reference/diagnostics#UF3035) or [UF3038](/docs/reference/diagnostics#UF3038), as on any component. Component candidates take `class` and `style`, but no other attribute or listener falls through them yet ([UF1002](/docs/reference/diagnostics#UF1002)).

## A known set

`is` chooses from a set the compiler knows when it compiles: a conditional or a literal whose leaves are all tags or all components, or a prop typed as a union of tag literals. Angular writes every candidate, and the typed targets check each one, so a value only the run time knows, such as a string from an API, is [UF3044](/docs/reference/diagnostics#UF3044), and so is a set that mixes tags and components. Write the candidates out in a conditional, or type the prop as a union of tags.

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-0055](https://github.com/uxfront-com/unframework/blob/main/docs/adrs/0055-composition-ir-capabilities-and-codes.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).
