React Teleporter

3.2.0 · active · verified Sun Apr 19

React Teleporter is a library designed for seamlessly moving or "teleporting" React components within the same React component tree. Unlike standard React Portals, which can render children into a different DOM node outside the current DOM hierarchy, `react-teleporter` maintains the logical connection within the same React tree. This distinction simplifies state and context management, as components remain within their original React context, making it ideal for managing complex layouts where content needs to appear in a different visual location than where it's defined. Inspired by the configuration philosophy of `react-helmet`, it allows for configuring parts of an application from a separate, perhaps deeply nested, location. The current stable version is 3.2.0, with regular minor and patch releases to support new React versions (currently up to React 19) and add features like `function as children` for `Source` components. Major versions, such as v3.0.0, introduce significant breaking changes, notably the transition to an ESM-only distribution. The library exports `createTeleporter`, which generates a `Source` and `Target` pair, enabling content defined within a `Source` component to be rendered at the `Target`'s designated position.

Common errors

Warnings

Install

Imports

Quickstart

This quickstart demonstrates how to use `createTeleporter` to define a `StatusBar` teleporter, allowing content from a `Source` component within `Page` to be rendered at a `Target` location inside `Header`, effectively moving UI elements across the React tree without prop drilling.

import { createTeleporter } from "react-teleporter";
import React from "react";
import ReactDOM from "react-dom/client";

const StatusBar = createTeleporter();

function Header() {
  return (
    <header style={{ borderBottom: "1px solid #ccc", padding: "10px" }}>
      <h2>My App Header</h2>
      <StatusBar.Target />
    </header>
  );
}

function Page() {
  return (
    <main style={{ padding: "20px" }}>
      <p>This is the main content of the page.</p>
      {/* Teleport "Loading..." into the header */}
      <StatusBar.Source>
        <div style={{ color: "blue", fontWeight: "bold" }}>Loading content...</div>
      </StatusBar.Source>
      <p>More page content here.</p>
    </main>
  );
}

function App() {
  return (
    <div>
      <Header />
      <Page />
    </div>
  );
}

const rootElement = document.getElementById("root");
if (rootElement) {
  ReactDOM.createRoot(rootElement).render(
    <React.StrictMode>
      <App />
    </React.StrictMode>
  );
} else {
    console.error("Root element not found");
}

view raw JSON →