Components

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:

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:

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

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:

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

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. A component whose whole render is a <Teleport> takes no class or style from its parent, 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, 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. The rule is on the semantics page.

Copyright © 2026