Logo

dev-resources.site

for different kinds of informations.

React Portals Explained

Published at
9/28/2024
Categories
react
portals
webdev
Author
imyusufakhtar
Categories
3 categories in total
react
open
portals
open
webdev
open
Author
13 person written this
imyusufakhtar
open
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.

Featured ones: