What is Portal in React: Simple Explanation and Example
portal lets you render a component's children into a different part of the DOM tree outside the parent component's hierarchy. It helps when you want to visually break out of the normal component structure, like for modals or tooltips.How It Works
Imagine you have a box inside a bigger box, and you want to put a small note inside the smaller box but have it appear outside the bigger box instead. React portals do something similar by letting you render a component's content somewhere else in the webpage's structure, not just inside its parent component.
This works by creating a special connection between your React component and a DOM node you choose elsewhere in the HTML. React keeps the component's logic and state as usual but moves the visible part to the chosen place. This is useful because sometimes UI elements like pop-ups or menus need to appear above everything else, ignoring the usual nesting rules.
Example
This example shows a simple modal dialog rendered using a React portal. The modal appears outside the main app container but still works with React's state and events.
import React, { useState } from 'react'; import { createPortal } from 'react-dom'; const modalRoot = document.getElementById('modal-root'); function Modal({ children, onClose }) { return createPortal( <div style={{ position: 'fixed', top: 0, left: 0, right: 0, bottom: 0, backgroundColor: 'rgba(0,0,0,0.5)', display: 'flex', justifyContent: 'center', alignItems: 'center' }}> <div style={{ background: 'white', padding: '20px', borderRadius: '8px' }}> {children} <button onClick={onClose}>Close</button> </div> </div>, modalRoot ); } export default function App() { const [showModal, setShowModal] = useState(false); return ( <div> <h1>Hello React Portal</h1> <button onClick={() => setShowModal(true)}>Open Modal</button> {showModal && <Modal onClose={() => setShowModal(false)}>This is a modal!</Modal>} </div> ); }
When to Use
Use portals when you need to render UI elements that visually break out of their parent container's bounds. Common cases include:
- Modals or dialogs that appear above all other content
- Tooltips that need to overlay other elements
- Dropdown menus that should not be clipped by parent containers
- Notifications or pop-ups that require a different DOM position for styling or accessibility
Portals keep your React component logic intact while letting you control where the content appears in the HTML, solving many layout and styling challenges.
Key Points
- Portals render children into a DOM node outside the parent component's DOM hierarchy.
- They help with UI elements that need to visually escape container boundaries.
- React keeps event handling and state working normally with portals.
- Use
createPortalfromreact-domto create portals.