# Teleport

> <Teleport to> mounts an element elsewhere on the page, like a dialog. Every framework mounts it once the component has mounted, never on the server.

Teleport lets a component render an element somewhere else in the page, outside its own box, like a dialog, a menu or a toast that sits over everything else. In Unframework you write `<Teleport to="body">` around it, and every framework mounts it at the end of `body` once the component has mounted. Think of a dialog clipped by the card that opens it because of an `overflow: hidden`, or a menu that a parent's `z-index` hides.

This page walks you through teleporting an element, and what the compiler checks. We'll look at:

- **An element elsewhere:** `<Teleport to>`, and what each framework receives.
- **A dialog:** opening, focusing and closing an overlay.
- **What it holds:** one element, a static selector, and what isn't guaranteed.

## An element elsewhere

Import `Teleport` and write it as a tag, with the selector of the element it mounts into as `to`. It holds one element, which may hold anything, and reads the component's state as the rest of the template does:

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

export interface NoticeProps {
  message: string;
}

export default function Notice({ message }: NoticeProps) {
  const dismissed = ref(0);

  return (
    <section class="inbox" aria-label="Inbox">
      <p>Dismissed {dismissed.value} times</p>
      <Teleport to="body">
        <div data-teleported class="notice">
          <p role="status">
            {message} ({dismissed.value})
          </p>
          <button type="button" onClick={() => dismissed.value++}>
            Dismiss
          </button>
        </div>
      </Teleport>
    </section>
  );
}
```

The server renders the section alone, and the notice mounts at the end of `body` once the component has mounted. Vue writes its own `<Teleport>`, React portals the element through react-dom's `createPortal`, Solid inserts it without the `<div>` its `<Portal>` adds, and Svelte, Angular and Qwik move the element with a small helper. Astro renders once, on the server, so it renders none of it:

::framework-switcher

#react

<!-- prettier-ignore -->
```tsx [Notice.tsx]
import {
  type CSSProperties,
  type ReactNode,
  type ReactPortal,
  useRef,
  useState,
  useSyncExternalStore,
} from "react";
import { createPortal } from "react-dom";

export interface NoticeProps {
  message: string;
}

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

export default function Notice({
  message,
  className,
  style,
  ...attributes
}: NoticeProps & NoticeAttributes) {
  const [dismissed, setDismissed] = useState(0);
  const dismissedRef = useRef(dismissed);
  const mounted = useSyncExternalStore(
    subscribeNothing,
    () => true,
    () => false,
  );

  return (
    <section
      className={cx("inbox", className)}
      aria-label="Inbox"
      style={style}
      {...scopeAttributes(attributes)}
    >
      <p>Dismissed {dismissed} times</p>
      {mounted
        ? teleport(
            <div data-teleported="true" className="notice">
              <p role="status">
                {message} ({dismissed})
              </p>
              <button
                type="button"
                onClick={() => {
                  dismissedRef.current++;
                  setDismissed(dismissedRef.current);
                }}
              >
                Dismiss
              </button>
            </div>,
            "body",
          )
        : null}
    </section>
  );
}

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

/** Subscribes to nothing: whether the component has mounted never changes once it has. */
function subscribeNothing(): () => void {
  return () => {};
}

/** Portals `children` into the element `to` selects, or renders nothing where none does. */
function teleport(children: ReactNode, to: string): ReactPortal | null {
  const target = document.querySelector(to);
  return target ? createPortal(children, target) : null;
}
```

#vue

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

export interface NoticeProps {
  message: string;
}

const { message } = defineProps<NoticeProps>();

const dismissed = ref(0);
const mounted = ref(false);

onMounted(() => {
  mounted.value = true;
});
</script>

<template>
  <section class="inbox" aria-label="Inbox">
    <p>Dismissed {{ dismissed }} times</p>
    <Teleport v-if="mounted" to="body">
      <div data-teleported="true" class="notice">
        <p role="status">{{ message }} ({{ dismissed }})</p>
        <button type="button" @click="dismissed++">Dismiss</button>
      </div>
    </Teleport>
  </section>
</template>
```

#svelte

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

<script lang="ts" module>
  export interface NoticeProps {
    message: string;
  }
</script>

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

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

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

  let dismissed = $state(0);

  let mounted = $state(false);

  onMount(() => {
    mounted = true;
  });

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

  /** Moves the element into the element `to` selects, and removes it on teardown. */
  function teleport(to: string): (element: HTMLElement) => () => void {
    return (element) => {
      const target = document.querySelector(to);
      if (!target) element.remove();
      else {
        const active = document.activeElement;
        target.append(element);
        // Moving a node blurs what it holds, which a component inside it may have focused.
        if (active instanceof HTMLElement && element.contains(active)) active.focus();
      }
      return () => element.remove();
    };
  }
</script>

<section class={["inbox", className]} aria-label="Inbox" {style} {...scopeAttributes(attributes)}>
  <p>Dismissed {dismissed} times</p
  >{#if mounted}
    <div {@attach teleport("body")} data-teleported="true" class="notice">
      <p role="status">{message} ({dismissed})</p
      ><button type="button" onclick={() => dismissed++}>Dismiss</button>
    </div>
  {/if}
</section>
```

#angular

<!-- prettier-ignore -->
```ts [notice.ts]
import {
  ApplicationRef,
  Component,
  DOCUMENT,
  DestroyRef,
  Directive,
  ElementRef,
  type EmbeddedViewRef,
  type OnInit,
  Renderer2,
  TemplateRef,
  afterEveryRender,
  inject,
  input,
  signal,
} from "@angular/core";

export interface NoticeProps {
  message: string;
}

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

/** The teleports a render created, which mount in the document's order. */
const TeleportQueue: { anchor: Node; mount: () => void }[] = [];

/** Mounts its template's content into the element `ufTeleport` selects once rendered, and removes it on destroy. */
@Directive({ selector: "ng-template[ufTeleport]" })
export class Teleport implements OnInit {
  readonly ufTeleport = input.required<string>();
  readonly ufTeleportHost = input<HTMLElement>();
  private readonly renderer = inject(Renderer2);

  ngOnInit(): void {
    const host = this.ufTeleportHost();
    for (const name of host?.getAttributeNames() ?? []) {
      if (name.startsWith("data-uf-")) this.renderer.removeAttribute(host, name);
    }
  }

  constructor() {
    const template = inject<TemplateRef<unknown>>(TemplateRef);
    const application = inject(ApplicationRef);
    const document = inject(DOCUMENT);
    const anchor: Node = inject<ElementRef<Comment>>(ElementRef).nativeElement;
    let view: EmbeddedViewRef<unknown> | undefined;
    const mount = () => {
      const target = document.querySelector(this.ufTeleport());
      if (!target) return;
      view = template.createEmbeddedView({});
      application.attachView(view);
      view.detectChanges();
      target.append(...view.rootNodes);
    };
    const unmount = () => {
      const nodes: Node[] = view?.rootNodes ?? [];
      view?.destroy();
      view = undefined;
      for (const node of nodes) node.parentNode?.removeChild(node);
    };
    // Angular runs a render's callbacks in no source order: each teleport queues itself, and the
    // first to write mounts them all in the order of their anchors. A template projected into a
    // slot that isn't rendered has no anchor in the document, so it waits for one.
    afterEveryRender({
      earlyRead: () => {
        if (!view && anchor.isConnected) TeleportQueue.push({ anchor, mount });
      },
      write: () => {
        const due = TeleportQueue.splice(0).sort((a, b) =>
          a.anchor.compareDocumentPosition(b.anchor) & Node.DOCUMENT_POSITION_FOLLOWING ? -1 : 1,
        );
        for (const each of due) each.mount();
        // The view reads the component's state, which this render may have changed.
        if (view && !anchor.isConnected) unmount();
        else view?.detectChanges();
      },
    });
    inject(DestroyRef).onDestroy(unmount);
  }
}

@Component({
  selector: "uf-notice",
  imports: [ScopeAttributes, Teleport],
  host: { "[attr.class]": "null", "[attr.style]": "'display: contents;'" },
  preserveWhitespaces: false,
  template: `
    @let message = this.message();
    @let dismissed = this.dismissed();
    <section
      class="inbox"
      aria-label="Inbox"
      [class]="this.class()"
      [style]="this.style()"
      [ufScope]="this.host"
    >
      <p>Dismissed {{ dismissed }} times</p>
      <ng-template ufTeleport="body">
        <div data-teleported="true" class="notice">
          <p role="status">{{ message }} ({{ dismissed }})</p>
          <button type="button" (click)="onDismiss()">Dismiss</button>
        </div>
      </ng-template>
    </section>
  `,
})
export default class Notice {
  readonly message = input.required<string>();
  readonly class = input<string>();
  readonly style = input<Record<string, string | null | undefined>>();
  protected readonly dismissed = signal(0);

  protected onDismiss() {
    this.dismissed.update((dismissed) => dismissed + 1);
  }
  protected readonly host = inject<ElementRef<HTMLElement>>(ElementRef).nativeElement;
}
```

#solid

<!-- prettier-ignore -->
```tsx [Notice.tsx]
import { type JSX, createRoot, createSignal, getOwner, onCleanup, onMount } from "solid-js";
import { insert } from "solid-js/web";

export interface NoticeProps {
  message: string;
}

export default function Notice(props: NoticeProps & { class?: string; style?: JSX.CSSProperties }) {
  const [dismissed, setDismissed] = createSignal(0);

  return (
    <section
      class={props.class ? `inbox ${props.class}` : "inbox"}
      aria-label="Inbox"
      style={props.style}
      {...scopeAttributes(props)}
    >
      <p>Dismissed {dismissed()} times</p>
      <Teleport to="body">
        <div data-teleported="true" class="notice">
          <p role="status">
            {props.message} ({dismissed()})
          </p>
          <button type="button" onClick={() => setDismissed(dismissed() + 1)}>
            Dismiss
          </button>
        </div>
      </Teleport>
    </section>
  );
}

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

/** Mounts `children` into the element `to` selects once the component has mounted, and removes them with it. */
function Teleport(props: { to: string; children: JSX.Element }): JSX.Element {
  const owner = getOwner();
  onMount(() => {
    const target = document.querySelector(props.to);
    if (!target) return;
    const [removed, remove] = createSignal(false);
    createRoot(
      (dispose) => insert(target, () => (removed() ? dispose() : props.children), null),
      owner,
    );
    onCleanup(() => remove(true));
  });
  return null;
}
```

#qwik

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

export interface NoticeProps {
  message: string;
}

export default component$<NoticeProps & { class?: ClassList; style?: CSSProperties }>(
  ({ message, class: className, style, ...attributes }) => {
    const dismissed = useSignal(0);

    const mounted = useSignal(false);
    useVisibleTask$(
      () => {
        mounted.value = true;
      },
      { strategy: "document-ready" },
    );

    return (
      <section
        class={["inbox", className]}
        aria-label="Inbox"
        {...scopeAttributes(attributes)}
        style={style}
      >
        <p>Dismissed {dismissed.value} times</p>
        {mounted.value && (
          <>
            {""}
            <div ref={teleport("body")} data-teleported="true" class="notice">
              <p role="status">
                {message} ({dismissed.value})
              </p>
              <button type="button" onClick$={() => dismissed.value++}>
                Dismiss
              </button>
            </div>
          </>
        )}
      </section>
    );
  },
);

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

/** The elements `teleport` has taken. */
const teleported = new WeakSet<Element>();

/** The element of a Qwik container, as Qwik selects it. */
const QWIK_CONTAINER = "[q\\:container]:not([q\\:container=html]):not([q\\:container=text])";

/**
 * A ref that moves its element into the element `to` selects once Qwik has inserted it, after the
 * empty text before it. The element sits after an empty text of its own in `to`, which keeps its
 * place: when Qwik moves the element with its component, it goes back after that text, whatever
 * else moved. It removes the element once the element that held it leaves the document: Qwik
 * removes the element itself with its branch, and only the outermost node of an element it
 * removes. It stops watching once the element is gone. Moved out of its Qwik container, the
 * element stands in for it, so its handlers still find their container.
 */
function teleport(to: string): (element: Element) => void {
  return (element) => {
    if (teleported.has(element)) return;
    teleported.add(element);
    let holder: Node | null = null;
    // Where the element sits in `to`: an empty text, which no capture shows and nothing else moves.
    const place = document.createTextNode("");
    const move = () => {
      const active = document.activeElement;
      place.after(element);
      // Moving a node blurs what it holds, which a component inside it may have focused.
      if (active instanceof HTMLElement && element.contains(active)) active.focus();
    };
    const observer = new MutationObserver(() => {
      if (holder === null) {
        if (!element.isConnected) return;
        holder = element.parentNode;
        const target = document.querySelector(to);
        if (!target || !holder || !element.previousSibling) {
          element.remove();
          observer.disconnect();
          return;
        }
        // Qwik finds a handler's container up from its element (`getDomContainer`): outside it,
        // the element stands in for it.
        const container = element.closest(QWIK_CONTAINER);
        if (container && target.closest(QWIK_CONTAINER) !== container) {
          element.setAttribute("q:container", container.getAttribute("q:container") ?? "");
          Object.assign(element, { qContainer: Reflect.get(container, "qContainer") });
        }
        target.append(place);
        move();
        return;
      }
      if (!holder.isConnected) {
        // An element around the teleport, or its component, has gone.
        element.remove();
      } else if (element.isConnected) {
        // Qwik moves a component's nodes with it, as a keyed list reorders it: back to its place.
        if (element.previousSibling !== place) move();
        return;
      }
      // Removed, by Qwik with its branch or here.
      place.remove();
      observer.disconnect();
    });
    observer.observe(document, { childList: true, subtree: true });
  };
}
```

#astro

<!-- prettier-ignore -->
```astro [Notice.astro]
---
export interface NoticeProps {
  message: string;
}

interface Props extends NoticeProps {
  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 dismissed = 0 as number;
---

<section
  class:list={["inbox", className]}
  aria-label="Inbox"
  style={style}
  {...scopeAttributes(Astro.props)}
>
  <p>Dismissed {dismissed} times</p>
</section>
```

::

## A dialog

Put a condition around the `<Teleport>` to open and close it. Code that needs the teleported elements goes in a component inside it, whose own `onMounted` runs once they're in the document, so this dialog focuses its Cancel button there:

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

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

export interface FilesProps {
  file: string;
}

export default function Files({ file }: FilesProps) {
  const emit = defineEmits<{ delete: [file: string] }>();
  const open = ref(false);

  function confirm() {
    open.value = false;
    emit("delete", file);
  }

  return (
    <section class="files" aria-label="Files">
      <p>{file}</p>
      <button type="button" onClick={() => (open.value = true)}>
        Delete {file}
      </button>
      {open.value && (
        <Teleport to="body">
          <div data-teleported class="backdrop">
            <ConfirmDialog
              title={`Delete ${file}?`}
              onConfirm={confirm}
              onClose={() => (open.value = false)}
            />
          </div>
        </Teleport>
      )}
    </section>
  );
}
```

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

export interface ConfirmDialogProps {
  title: string;
}

export default function ConfirmDialog({ title }: ConfirmDialogProps) {
  const emit = defineEmits<{ confirm: []; close: [] }>();
  const titleId = useId();
  const cancel = useTemplateRef<HTMLButtonElement>();

  // Inside the teleport, so its element is in the document when this runs (ADR-0098).
  onMounted(() => {
    cancel.value?.focus();
  });

  function onKeydown(event: KeyboardEvent) {
    if (event.key === "Escape") emit("close");
  }

  return (
    <div
      role="dialog"
      aria-modal="true"
      aria-labelledby={titleId}
      tabindex="-1"
      class="dialog"
      onKeydown={onKeydown}
    >
      <h2 id={titleId}>{title}</h2>
      <button type="button" ref={cancel} onClick={() => emit("close")}>
        Cancel
      </button>
      <button type="button" onClick={() => emit("confirm")}>
        Delete
      </button>
    </div>
  );
}
```

Closing the dialog removes it from `body`, and so does unmounting the component that holds it.

## What it holds

The content of `<Teleport>` is exactly one element. Text, two elements, a component, a conditional or a list as the content is rejected, [UF3054](/docs/reference/diagnostics#UF3054): wrap them in one element, and put a condition around the `<Teleport>`. `to` is a string literal. A bound or empty `to` is rejected, [UF3053](/docs/reference/diagnostics#UF3053):

<!-- prettier-ignore -->
```tsx [Overlay.uf.tsx]
// UF3053 teleport-target: `<Teleport to>` takes a static CSS selector, so a bound `to` and an
// empty one are rejected at the attribute.
import { Teleport } from "@uxfront/unframework";

export interface OverlayProps {
  target: string;
}

export default function Overlay({ target }: OverlayProps) {
  return (
    <section>
      <Teleport to={target}>
        <div class="overlay">Bound</div>
      </Teleport>
      <Teleport to="">
        <div class="overlay">Empty</div>
      </Teleport>
    </section>
  );
}
```

The element is checked where the `<Teleport>` is, as an element there would be, so a `<div>` teleported from inside a `<p>` is rejected, [UF3003](/docs/reference/diagnostics#UF3003). A component whose whole render is a `<Teleport>` takes no `class` or `style` from its parent, [UF3045](/docs/reference/diagnostics#UF3045), and its own styles follow the element wherever it mounts.

A few things aren't guaranteed:

- The `onMounted` of the component that holds the `<Teleport>` may run before the content exists. A component inside the teleport sees it in its own.
- Whether an element outside the teleport hears an event from inside it. [React's events bubble through a portal](https://react.dev/reference/react-dom/createPortal), the browser's don't, so listen inside the teleported element.
- What happens when `to` matches no element. Each framework renders nothing.
- A selector across the boundary. `.panel .dialog` no longer matches a teleported `.dialog`, while `.dialog` and what it holds still do.

The decision behind this page is [ADR-0098](https://github.com/uxfront-com/unframework/blob/main/docs/adrs/0098-teleport.md). The rule is on [the semantics page](/docs/reference/semantics#teleport).
