Join the discussion
Comments
Loading comments...
Cookie preferences
We use essential cookies for sign-in and preferences. With your permission, we also use basic analytics to improve lessons.
Join the discussion
Loading comments...
We use essential cookies for sign-in and preferences. With your permission, we also use basic analytics to improve lessons.
Rendering von Kindern außerhalb der übergeordneten DOM-Hierarchie bei Beibehaltung des React-Event-Bubblings.
ReactDOM.createPortal(kinder, domKnoten) rendert einen React-Teilbaum in einen anderen DOM-Knoten als den, in dem der Elternteil rendert. Obwohl die Komponente an einem anderen Ort im DOM erscheint (z.B. ein Modal auf Body-Ebene), bleibt sie ein Kind im React-Komponentenbaum. Das bedeutet, dass Kontext, Ereignisse und React-Lifecycle genau so funktionieren, als ob das Portal eingebettet wäre.
createPortal(kinder, document.getElementById('modal-root')) weist React an, Kinder in #modal-root anstatt in den DOM-Teilbaum des Elternteils zu rendern. Die DOM-Ausgabe ist vollständig getrennt vom DOM des Elternteils.
Trotz des Renderings an anderer Stelle im DOM ist die Portal-Komponente konzeptionell ein Kind der Komponente, die es rendert. Es erhält dieselben Kontextwerte, dieselben React-Props und nimmt am selben Fiber-Baum teil.
Wenn Sie innerhalb eines Portals klicken, blubbert das Click-Ereignis durch Reacts Komponentenbaum zum Elternteil — auch wenn im DOM der Knoten des Portals außerhalb des DOM-Teilbaums des Elternteils liegt. Reacts synthetisches Ereignissystem operiert auf dem Fiber-Baum, nicht dem DOM-Baum.
Eine Portal-Komponente kann Kontextwerte von einem Provider lesen, der ein Vorfahre in Reacts Komponentenbaum ist, auch wenn das Portal in einen völlig anderen DOM-Knoten rendert.
ReactDOM.createPortal(kinder, domKnoten). Rendert React-Kinder in domKnoten anstatt in den DOM-Container des Elternteils.
Zwei verschiedene Hierarchien. Der React-Baum regelt Kontext, Ereignisse und Props. Der DOM-Baum regelt visuelles Layout und CSS-Vererbung.
Portal-Ereignisse blubbern durch den React-Komponentenbaum (nicht DOM-Baum), sodass Eltern-Komponenten Ereignisse von Portal-Kindern empfangen.
Häufigster Portal-Anwendungsfall: Modals und Tooltips auf document.body rendern, um overflow:hidden oder z-index-Clipping von Vorfahren-Elementen zu vermeiden.
1import { createPortal } from 'react-dom';23function Modal({ isOpen, onClose, children }) {4 if (!isOpen) return null;56 // Renders into document.body, not into parent's DOM node7 return createPortal(8 <div className="modal-overlay" onClick={onClose}>9 <div className="modal-content" onClick={e => e.stopPropagation()}>10 {children}11 </div>12 </div>,13 document.body // the target DOM node14 );15}1617// Usage — modal is a React child of Card,18// but renders at document.body in the DOM19function Card() {20 const [open, setOpen] = useState(false);21 return (22 <div style={{ overflow: 'hidden' }}> {/* won't clip modal */}23 <button onClick={() => setOpen(true)}>Open Modal</button>24 <Modal isOpen={open} onClose={() => setOpen(false)}>25 Content here!26 </Modal>27 </div>28 );29}
Portale lösen ein grundlegendes CSS-Problem: Modals, Tooltips und Dropdowns müssen visuell aus ihren übergeordneten Containern 'entkommen'. Vorfahren-CSS wie overflow:hidden, z-index-Stapelkontexte und transform-Eigenschaften können absolut positionierte Kinder beschneiden oder repositionieren. Durch das Rendern auf document.body umgehen Portale all diese Einschränkungen, während Reacts Komponentenmodell erhalten bleibt.
Your card component has `overflow: hidden` to clip long text. When you add a dropdown menu or modal inside the card, it gets clipped by the card's overflow — users can't see the full dropdown.
The modal/dropdown is a DOM child of the card, so CSS `overflow: hidden` on the card clips everything inside it. You could remove overflow:hidden but that breaks the text truncation. CSS `z-index` alone can't escape an overflow context.
Use a portal to render the modal at `document.body`. It escapes the card's CSS stacking context entirely. React events still bubble through the React tree (card → modal), so onClick handlers and context providers work normally — only the DOM position changes.
Takeaway: Portals decouple the DOM hierarchy from the React component hierarchy. This is essential for any UI that needs to visually 'break out' of its container: modals, tooltips, dropdowns, toast notifications, and floating menus.
You're building a micro-frontend where your React widget needs to render inside a specific container managed by a host application (not your root div). The host gives you a `#widget-container` div.
Your React app renders into `#app-root` by default. You can't simply move your component tree because it needs to share context and state with other parts of your React app.
Use portals to render specific components into `#widget-container` while keeping them in the same React tree. They still receive context from their React parent, participate in event bubbling, and share state — they just render into a different DOM node.
Takeaway: Portals are the foundation for micro-frontend integration patterns. They let you mount React components into external DOM nodes while preserving the full React component model (context, error boundaries, event delegation).