Portal
The Portal Component uses React.createPortal
to render the Child Component on a DOM Element outside of the Parent Component's DOM hierarchy.
The Portal Component renders a Child Component in document.body
by default. However, if you pass in the Portal Component's containerRef
prop, you can render the Child Component in a different DOM Element
than document.body
.
Additionally, it supports nested portal functionality
. Nesting multiple Portal Components creates a nested portal DOM hierarchy
.
The Portal Component is ideal for use with features like Modal
, Dialog
, and Tooltip
.
React CreatePortal Please refer to the following articles
Interface
const Portal: ({ children, className, containerRef }: {
children: React.ReactNode;
className?: string;
containerRef?: React.RefObject<HTMLElement>;
}) => JSX.Element
Usage
Default
import { Portal } from '@devgrace/react'
const Example = () => {
return (
<Portal>
<p>Example Portal</p>
</Portal>
);
};
Container
import { Portal } from '@devgrace/react'
const Example = () => {
const ref = useRef<HTMLDivElement | null>(null);
return (
<div>
<Portal containerRef={ref}>
<p>Example Portal</p>
</Portal>
<div id="outer" ref={ref} />
</div>
);
};
Nested
import { Portal } from '@devgrace/react'
const Example = () => {
return (
<Portal>
<p>Default Portal</p>
<Portal>
<p>Nested Portal1</p>
<Portal>
<p>Nested Portal2</p>
</Portal>
</Portal>
</Portal>
);
};