How to use portals in React

Rendering React components outside their normal DOM hierarchy is crucial for creating modals, tooltips, and overlays that need to escape parent container constraints. As the creator of CoreUI with over 25 years of development experience building React applications since 2014, I’ve implemented portals extensively in our modal and dropdown components to handle z-index and overflow issues. The most reliable approach is using ReactDOM.createPortal() to render components into a different DOM node while maintaining React’s component tree and event handling. This technique ensures proper styling and accessibility for overlay components that need to appear above other content.

Use ReactDOM.createPortal() to render a component into a different DOM node outside the normal component hierarchy.

import { createPortal } from 'react-dom'

function Modal({ isOpen, children }) {
  if (!isOpen) return null

  return createPortal(
    <div className="modal-overlay">
      <div className="modal-content">
        {children}
      </div>
    </div>,
    document.getElementById('modal-root')
  )
}

The createPortal() function takes two arguments: the JSX to render and the target DOM element where it should be rendered. Even though the component renders outside its parent DOM node, it maintains its position in the React component tree, so props, state, and context work normally. Events also bubble up through the React tree, not the DOM tree, which ensures consistent event handling. This makes portals perfect for modals, tooltips, and dropdowns that need to escape overflow:hidden containers.

Best Practice Note:

This is the technique we use in CoreUI React components for all overlay elements like modals and dropdowns to ensure they render above other content. Always create a dedicated DOM element like <div id="modal-root"></div> in your HTML for portal targets and ensure it exists before rendering.


Speed up your responsive apps and websites with fully-featured, ready-to-use open-source admin panel templates—free to use and built for efficiency.


About the Author

Subscribe to our newsletter
Get early information about new products, product updates and blog posts.
How to sleep in Javascript
How to sleep in Javascript

JavaScript printf equivalent
JavaScript printf equivalent

What is the difference between sort and toSorted in JavaScript?
What is the difference between sort and toSorted in JavaScript?

How to declare the optional function parameters in JavaScript?
How to declare the optional function parameters in JavaScript?

Answers by CoreUI Core Team