# 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 attributes and children apply to whichever tag renders:

<!-- 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 CSSProperties, useRef, useState } from "react";

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

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} {...scopeAttributes(attributes)}>
      <Tag className="title">{title}</Tag>
      <button
        type="button"
        onClick={() => {
          nestedRef.current = !nestedRef.current;
          setNested(nestedRef.current);
        }}
      >
        {nested ? "Lift" : "Nest"}
      </button>
    </article>
  );
}

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

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

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

  let nested = $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>

<article class={className} {style} {...scopeAttributes(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 {
  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-section",
  imports: [ScopeAttributes],
  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()" [ufScope]="this.host">
      @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>>();
  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 JSX, createSignal } from "solid-js";
import { Dynamic } from "solid-js/web";

export default function Section(
  props: { title: string } & { class?: string; style?: JSX.CSSProperties },
) {
  const [nested, setNested] = createSignal(false);

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

/** 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 [Section.tsx]
import { type CSSProperties, type ClassList, component$, useSignal } from "@qwik.dev/core";

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

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

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

/** 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 [Section.astro]
---
interface Props {
  title: string;
  class?: string;
  style?: Record<string, string | number | undefined>;
}

const { title, 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 nested = false as boolean;

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

<article class:list={[className]} style={style} {...scopeAttributes(Astro.props)}>
  <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).

Every attribute must be valid on every candidate, since any of them may render: an attribute one tag doesn't take is [UF3006](/docs/reference/diagnostics#UF3006), for that tag.

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

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

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