35) Portals
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>Why use Portals?
i) Z-index / Overflow issues
Parent may haveoverflow: 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 constraintsKey Characteristics
Part of same React component tree
Only DOM position changes
Context & state still accessible
Events bubble normallyBest Practices
Create a dedicated root (#modal-root)
Handle accessibility (focus trap, ARIA roles)
Clean up on unmount
Reuse portal components (like<Modal />)