Sobes.tech
Middle+

What are portals (createPortal) in React?

sobes.tech AI

Answer from AI

React portals (createPortal) allow rendering child elements of a component into a DOM node that exists outside the hierarchy of the parent component.

This is useful when you need to display a modal window, tooltip, or context menu that should be visually outside the current container but logically related to the component.

Example usage:

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

function Modal({ children }) {
  return ReactDOM.createPortal(
    <div className="modal">
      {children}
    </div>,
    document.getElementById('modal-root') // element outside the main app root
  );
}

Here, the modal content will be inserted into the element with id modal-root, which can be located anywhere in the DOM, helping to avoid issues with CSS styles or positioning context.

What are portals (createPortal) in React? — Frontend - sobes.tech