React portal

React Portals is a feature in the React that provides a way to render a React component at a different location in the DOM instead of where it is declared.


React Portals is a feature in the React that provides a way to render a React component at a different location in the DOM instead of where it is declared. According to the React documentation, React Portals offer a method to render children into a DOM node that is not part of the parent component’s DOM hierarchy.

To create a portal, call createPortal, passing some JSX, and the DOM node where it should be rendered:

createPortal(children, domNode);

Parameters

  • children: Anything that can be rendered with React, such as a piece of JSX (e.g. <div /> or <SomeComponent />), a Fragment (<>...</>), a string or a number, or an array of these.
  • domNode: Some DOM node, such as those returned by document.getElementById(). The node must already exist. Passing a different DOM node during an update will cause the portal content to be recreated.

returns

  • createPortal returns a React node that can be included into JSX or returned from a React component.

Usage

Rendering to a different part of the DOM

import { createPortal } from 'react-dom';
 
function MyComponent() {
  return (
    <div style={{ border: '2px solid black' }}>
      <p>This child is placed in the parent div.</p>
      {createPortal(
        <p>This child is placed in the document body.</p>,
        document.body
      )}
    </div>
  );
}
<body>
  <div id='root'>
    <div style='border: 2px solid black'>
      <p>This child is placed inside the parent div.</p>
    </div>
  </div>
  <p>This child is placed in the document body.</p>
</body>

Rendering a modal dialog with a portal

You can use a portal to create a React components such as modal dialog that floats above the rest of the page, even if the component that summons the dialog is inside a container with overflow: hidden or other styles that interfere with the dialog.

Reference

Latest Posts