Hack Frontend Community

What is Portal in React

Portal is a mechanism in React that allows rendering a component outside the main DOM tree, while still remaining part of the React hierarchy.

This is useful when you need to display modal windows, tooltips, dropdowns that shouldn't be nested within parent styles (e.g., overflow: hidden, z-index, transform).


How to Create a Portal?

React provides a special method:

ReactDOM.createPortal(children, container)
  • children — element to render
  • container — DOM element where JSX will be placed outside current tree

Portal Usage Example

import { createPortal } from 'react-dom';

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

HTML

<body>
  <div id="root"></div>
  <div id="modal-root"></div> <!-- portal renders here -->
</body>

Now Modal component won't be wrapped in #root parent styles, but React will still manage its state and lifecycle.

Where Are Portals Used?

  • Modal windows
  • Tooltips
  • Dropdowns
  • Notifications
  • Side panels

Advantages

  • Escape from CSS container limitations
  • No conflicts with z-index, overflow, position
  • React app remains managed (handlers, state, refs work as usual)

Important to Remember

  • Portals don't create new React context, they use same as parent
  • Can break layout if global styles aren't considered

Conclusion:

Portal is a powerful React tool when you want to visually break out of parent DOM, while maintaining React control. Use them for modals, tooltips and any UI elements that should be "on top" of everything.