</>
Skip to content
React lessons (41/47)

React — Portals

Basic Portal

import { createPortal } from 'react-dom';

function Modal({ children, onClose }) {
    return createPortal(
        <div className="modal-overlay">
            <div className="modal">
                <button onClick={onClose}>Close</button>
                {children}
            </div>
        </div>,
        document.body
    );
}

Using Portals

function App() {
    const [showModal, setShowModal] = useState(false);

    return (
        <div>
            <button onClick={() => setShowModal(true)}>Open Modal</button>

            {showModal && (
                <Modal onClose={() => setShowModal(false)}>
                    <h2>Modal Content</h2>
                    <p>This is rendered outside the DOM tree.</p>
                </Modal>
            )}
        </div>
    );
}

Portal Examples

// Tooltip
function Tooltip({ children, content }) {
    return (
        <div className="tooltip-container">
            {children}
            {createPortal(
                <div className="tooltip">{content}</div>,
                document.body
            )}
        </div>
    );
}

// Dropdown menu
function Dropdown({ trigger, children }) {
    const [isOpen, setIsOpen] = useState(false);

    return (
        <div className="dropdown">
            <div onClick={() => setIsOpen(!isOpen)}>{trigger}</div>
            {isOpen && createPortal(
                <div className="dropdown-menu">
                    {children}
                </div>,
                document.body
            )}
        </div>
    );
}

// Toast notifications
function ToastContainer({ toasts }) {
    return createPortal(
        <div className="toast-container">
            {toasts.map(toast => (
                <div key={toast.id} className="toast">
                    {toast.message}
                </div>
            ))}
        </div>,
        document.body
    );
}

When to Use Portals

  1. Modals and dialogs
  2. Tooltips
  3. Dropdown menus
  4. Toast notifications
  5. Loading overlays

Mini Practice

Write React code that:

  1. Creates a modal with portal
  2. Renders a tooltip outside DOM
  3. Creates a dropdown menu
  4. Implements toast notifications

Up Next

Next: Learn about Suspense.

Related Topics

Frequently Asked Questions about Portals

What is Portals in React?

Portals is a fundamental concept in React. This lesson explains it step by step with clear examples, making it easy for beginners to understand.

How do I learn Portals?

Start by reading the explanation above, then try the code examples. Practice by modifying the examples and experimenting with different values. Hands-on practice is the best way to learn Portals.

Why is Portals important in React?

Portals is essential for React development. Understanding this concept will help you write better code and solve real-world problems more effectively.