Chakra-UI


Portal

|

Chakra Docs

|

⦾ The Portal component is a powerful tool for rendering components outside of the current DOM hierarchy. The Portal allows you to create a separate DOM hierarchy, making it useful for scenarios like popovers, dropdowns, and modals.

The Portal component in Chakra UI enables the rendering of React components or elements at the end of the document.body. This functionality ensures that the rendered content exists in a different DOM hierarchy, preventing parent styles from clipping or hiding the content. Additionally, thePortal component supports nested portals, which enables the creation of complex nested modals, popovers, and more.

The Portal component can be imported as follows:

Examples

Basic Usage


⦾ In this example, we have a Box component, within which we include a Portal component, and the text inside the Portal will be rendered at the end of the document.body.
The portaled text inside will not show up here.

Code

Custom Container Portal


⦾ The Portal component allows you to specify a custom container to render the portal contents instead of the default document.body. To achieve this, you can use the containerRef prop and set its value to the ref of the desired container.

In this example, we have a Box component as the main container. Inside the Box, we have a Portal component with a custom container specified by the containerRef prop. The portal content will be rendered within the Box instead of the document.body, allowing for greater control over the rendering location.

Parent of the Portal.
Container to which the Portal is portaled!

Code

Nested Portals


⦾ The Portal component also supports nesting, allowing you to create nested modals, popovers, and more.

In this example, we have a parent Portal component and a child Portal component nested within it. This nesting creates a hierarchical structure, allowing for the creation of complex UI components like nested modals. The child portal content will be rendered within the parent portal's DOM hierarchy.

Code

Preventing Nested Portals


⦾ In some cases, you may want to prevent portal nodes from being nested within their parent portals. The Portal component provides the appendToParentPortal prop to opt out of this nesting behavior. In this example, the child Portal component has the appendToParentPortal prop set to false, ensuring that the child portal content is rendered directly under document.body instead of being nested within the parent portal's DOM hierarchy.

Code

copyright © 2023 IHeartComponents | evanmarie.com

Chakra-UIRemix

Special thanks to Stefan Bohacek / Generative Placeholders.