Skip to content

Instantly share code, notes, and snippets.

@zemd
Created March 23, 2024 09:27
Show Gist options
  • Save zemd/c9d394006a4a03d1e0abb4f1fd9f9f5d to your computer and use it in GitHub Desktop.
Save zemd/c9d394006a4a03d1e0abb4f1fd9f9f5d to your computer and use it in GitHub Desktop.
Minimal sufficient Portal implementation for react.js
"use client";
import { createPortal } from "react-dom";
const getContainer = (container: TPortalProps["container"]) => {
return typeof container === "function" ? container() : container;
};
type TPortalProps = React.PropsWithChildren<{
container?: Element | (() => Element | null) | null;
}>;
export const Portal: React.FC<TPortalProps> = ({ children, container }) => {
const moundNode = getContainer(container);
return createPortal(children, moundNode ?? document.body);
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment