Skip to main content
react-md

Portal

A Portal lets you render some children into a different part of the DOM. The Portal component is a simple wrapper around the createPortal that renders everything in the document.body or a <div id="rmd-portal-container" />.

See the PortalContainerProvider to see how to change the portal container on an app level.

This is mostly an internal component for react-md and doesn't have many use-cases other than rendering all elements into a specific container element.

Simple Example

When the app is wrapped in the CoreProviders or PortalContainerProvider, all portalled elements will be rendered within a <div id="rmd-portal-container" /> which is usually the last element within the document.body.

"use client";

import { Button } from "@react-md/core/button/Button";
import { Portal } from "@react-md/core/portal/Portal";
import { black } from "@react-md/core/theme/colors";
import { useToggle } from "@react-md/core/useToggle";
import { type ReactElement } from "react";

export default function SimplePortalExample(): ReactElement {
  const { toggled, toggle } = useToggle();
  return (
    <>
      <Button onClick={toggle}>Toggle Portal</Button>
      {toggled && (
        <Portal>
          <span
            style={{
              position: "fixed",
              top: "50%",
              left: "50%",
              backgroundColor: black,
              padding: "3rem",
              zIndex: 100,
              transform: "translate(-50%, -50%)",
            }}
          >
            This is rendered out of the normal react tree
          </span>
        </Portal>
      )}
    </>
  );
}

Press Enter to start editing.