Skip to content
","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"}
React

Portal

Render to DOM nodes outside the component.

By EZ4Code Team
reactportal

Code

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}>&times;</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>

Explanation

createPortal renders components to any DOM node, commonly used for modals, tooltips, avoiding z-index and overflow issues.

More React Snippets