🎉 75% of content is free forever — Unlock Premium from $10/mo →
CW
đŸ’ŧ Servicesâ„šī¸ Aboutâœ‰ī¸ ContactView Pricing Plansfrom $10

React Portals

React PatternsđŸŸĸ Free Lesson

Advertisement

React Portals

Rendering outside the DOM tree, modals, tooltips, and event bubbling.

Overview

Portals let you render children into a different part of the DOM while keeping React events.

Key Concepts

  • createPortal — Renders children into a different DOM node
  • Event Bubbling — Events still propagate through React tree
  • Use Cases — Modals, tooltips, dropdowns, notifications
  • CSS Isolation — Style portal content independently
  • SSR Considerations — Portals require client-side rendering

Code Examples

import { createPortal } from 'react-dom';

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.getElementById('modal-root')
  );
}

function App() {
  const [isModalOpen, setIsModalOpen] = useState(false);

  return (
    <div>
      <button onClick={() => setIsModalOpen(true)}>Open Modal</button>
      <Modal isOpen={isModalOpen} onClose={() => setIsModalOpen(false)}>
        <h2>Modal Content</h2>
        <p>This is rendered outside the main DOM tree.</p>
      </Modal>
    </div>
  );
}

Practice

Build a modal system with keyboard navigation and focus trapping.

Need Expert React Help?

Get personalized tutoring, project support, or professional consulting.

Advertisement