Sobes.tech
Middle+

What is React Portal, how does it work, and what are its features?

sobes.tech AI

Answer from AI

React Portal is a mechanism that allows rendering child components into a DOM node outside the hierarchy of the parent React component. This is useful when you need to visually or logically separate a part of the UI, such as modal windows, tooltips, or pop-up menus, which should appear above the rest of the content.

A portal is created using the function ReactDOM.createPortal(child, container), where child is a React element, and container is a DOM node where this element will be placed.

Features:

  • The portal preserves the React context, meaning events and state work as usual.
  • It helps avoid issues with CSS styles and z-index, as the element is rendered outside the main DOM tree of the component.
  • It is convenient for implementing UI elements that need to visually extend beyond the parent container.

Example of usage:

import React from 'react';
import ReactDOM from 'react-dom';

function Modal({ children }) {
  const modalRoot = document.getElementById('modal-root');
  return ReactDOM.createPortal(
    <div className="modal">
      {children}
    </div>,
    modalRoot
  );
}

export default Modal;

Here, the content of the modal window will be rendered into the element with id modal-root, which is outside the main application root.