","url":"https://ez4code.com/snippets/react-portal","keywords":"react, portal","author":{"@type":"Person","name":"EZ4Code Team"},"publisher":{"@type":"Organization","name":"EZ4Code","logo":{"@type":"ImageObject","url":"https://ez4code.com/logo.png"}},"datePublished":"2024-01-01","dateModified":"2026-08-01","image":"https://ez4code.com/og-image.png"}
Render to DOM nodes outside the component.
import { createPortal } from 'react-dom';
import { useState, useEffect } from 'react';
// Modal
function Modal({ isOpen, onClose, children }) {
if (!isOpen) return null;
return createPortal(
<div className="modal-overlay" onClick={onClose}>
<div className="modal-content" onClick={e => e.stopPropagation()}>
<button className="modal-close" onClick={onClose}>×</button>
{children}
</div>
</div>,
document.body
);
}
// Usage
function App() {
const [show, setShow] = useState(false);
return (
<div style={{ overflow: 'hidden', position: 'relative' }}>
<button onClick={() => setShow(true)}>Open Modal</button>
<Modal isOpen={show} onClose={() => setShow(false)}>
<h2>Modal Title</h2>
<p>Modal content here</p>
</Modal>
</div>
);
}
// Tooltip
function Tooltip({ target, content }) {
return createPortal(
<div className="tooltip" style={{
position: 'fixed',
top: target.rect.top - 30,
left: target.rect.left,
}}>
{content}
</div>,
document.body
);
}
// Confirm Portal position in DOM
// <div id="root">
// <App /> <-- Modal component here
// </div>
// <body>
// <div>Modal overlay</div> <-- Portal renders here
// </body>createPortal renders components to any DOM node, commonly used for modals, tooltips, avoiding z-index and overflow issues.
Build a controlled React form with inline validation and error messages.
Handle events and render dynamic lists with keys in React.
State management Hook.
Side-effect Hook.
Shared state via context.
Complex state management.