# 35) Portals

1.  **<mark class="bg-yellow-200 dark:bg-yellow-500/30">What is Portal</mark>**  
    **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
    
    ```javascript
    <div id="root">
      <App />
    </div>
    ```
    
    With a Portal, you can render a component somewhere else in the DOM
    
    ```javascript
    <div id="root"></div>
    <div id="modal-root"></div>
    ```
    
    React Component
    
    ```javascript
    import ReactDOM from "react-dom";
    
    const Modal = ({ children }) => {
      return ReactDOM.createPortal(
        <div className="modal">
          {children}
        </div>,
        document.getElementById("modal-root")
      );
    }
    ```
    
    Usage
    
    ```javascript
    <Modal>
      <h1>This is a modal</h1>
    </Modal>
    ```
    
2.  **<mark class="bg-yellow-200 dark:bg-yellow-500/30">Why use Portals?</mark>**  
    **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.  **<mark class="bg-yellow-200 dark:bg-yellow-500/30">Key Characteristics</mark>**  
    Part of same React component tree  
    Only DOM position changes  
    Context & state still accessible  
    Events bubble normally
    
4.  **<mark class="bg-yellow-200 dark:bg-yellow-500/30">Best Practices</mark>**  
    Create a dedicated root (`#modal-root`)  
    Handle accessibility (focus trap, ARIA roles)  
    Clean up on unmount  
    Reuse portal components (like `<Modal />`)
