Portal

The Portal component allows you to render a child component outside of its parent hierarchy, by creating a portal to another part of the DOM. This can be useful in situations where you need to render a component in a specific part of the page or outside of the component tree.

Installation

npm install @madeinhaus/portal

Import

import Portal from '@madeinhaus/portal';

Props

The Portal component accepts two props:

  • selector: A string representing the CSS selector for the DOM element where the portal will be created. If no selector is provided, the default selector #__portal__ will be used.
  • children: The child component(s) to be rendered within the portal.

Usage

Wrap your desired child component(s) within the Portal component:

function MyComponent() {
  return (
    <div>
      <h1>My Component</h1>
      <Portal>
        <div>
          <p>This component will be rendered outside of the parent hierarchy.</p>
        </div>
      </Portal>
    </div>
  );
}

In the above example, the div element containing the p element will be rendered outside of the parent hierarchy of MyComponent, and will be placed within an element selected by the selector prop of the Portal component.

Example

Here is an example of using the Portal component with a custom selector:

function MyComponent() {
  return (
    <div>
      <h1>My Component</h1>
      <Portal selector="#my-portal">
        <div>
          <p>This component will be rendered outside of the parent hierarchy in a custom portal.</p>
        </div>
      </Portal>
      <div id="my-portal"></div>
    </div>
  );
}

In this example, the div with the id my-portal is used as the selector for the portal. The Portal component will render the div containing the p element within the my-portal element, which is located outside of the parent hierarchy of MyComponent.