Skip to main content

Command Palette

Search for a command to run...

35) Portals

Updated
View as Markdown
  1. What is Portal
    Portals in React let you render a component outside its parent DOM hierarchy, while still keeping it part of the same React tree.
    Normally, a component renders inside its parent DOM node

    <div id="root">
      <App />
    </div>
    

    With a Portal, you can render a component somewhere else in the DOM

    <div id="root"></div>
    <div id="modal-root"></div>
    

    React Component

    import ReactDOM from "react-dom";
    
    const Modal = ({ children }) => {
      return ReactDOM.createPortal(
        <div className="modal">
          {children}
        </div>,
        document.getElementById("modal-root")
      );
    }
    

    Usage

    <Modal>
      <h1>This is a modal</h1>
    </Modal>
    
  2. Why use Portals?
    i) Z-index / Overflow issues
    Parent may have overflow: hidden
    Modal or dropdown gets clipped
    Portal renders it outside → problem solved
    ii) Better layering
    Modals, tooltips, popovers need to appear on top
    iii) Cleaner DOM structure
    Keeps UI logic separate from layout constraints

  3. Key Characteristics
    Part of same React component tree
    Only DOM position changes
    Context & state still accessible
    Events bubble normally

  4. Best Practices
    Create a dedicated root (#modal-root)
    Handle accessibility (focus trap, ARIA roles)
    Clean up on unmount
    Reuse portal components (like <Modal />)