DEV Community

Md Yusuf
Md Yusuf

Posted on

React Portals Explained

React Portals provide a way to render children components into a DOM node that exists outside the parent component's hierarchy. This is useful when you need to render components like modals, tooltips, or dropdowns that require positioning outside of the normal flow of the component tree for better styling or functionality.

Usage of React Portals:

  1. Creating a Portal:
    You use ReactDOM.createPortal to create a portal. It takes two arguments:

    • The children (elements to render).
    • The DOM node where the children should be rendered.
  2. Basic Example:

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

function Modal({ children }) {
  return ReactDOM.createPortal(
    <div className="modal">
      {children}
    </div>,
    document.getElementById('modal-root') // Specify the target DOM node.
  );
}

function App() {
  return (
    <div>
      <h1>Main App</h1>
      <Modal>
        <h2>This is a modal</h2>
      </Modal>
    </div>
  );
}

export default App;
Enter fullscreen mode Exit fullscreen mode

Explanation:

  • The modal content will be rendered into the DOM node with id="modal-root", which is outside the main app’s component tree.

Why use Portals?

  • Modals/Overlays: Ensures they are rendered outside the DOM tree to avoid clipping and z-index issues.
  • Tooltips/Dropdowns: Helps position these components more easily and avoid unwanted layout behavior.

Heroku

This site is built on Heroku

Join the ranks of developers at Salesforce, Airbase, DEV, and more who deploy their mission critical applications on Heroku. Sign up today and launch your first app!

Get Started

Top comments (0)

Sentry image

Hands-on debugging session: instrument, monitor, and fix

Join Lazar for a hands-on session where you’ll build it, break it, debug it, and fix it. You’ll set up Sentry, track errors, use Session Replay and Tracing, and leverage some good ol’ AI to find and fix issues fast.

RSVP here →

👋 Kindness is contagious

Please leave a ❤️ or a friendly comment on this post if you found it helpful!

Okay