πŸŽ‰ 75% of content is free forever β€” Unlock Premium from $10/mo β†’
CW
Search courses…
πŸ’Ό 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.

⭐

Premium Content

React Portals

Unlock this lesson and 900+ advanced tutorials with a Premium plan.

🎯End-to-end Projects
πŸ’ΌInterview Prep
πŸ“œCertificates
🀝Community Access

Already a member? Log in

Need Expert React Help?

Get personalized tutoring, project support, or professional consulting.

Advertisement