React Portals allow you to render components outside the main DOM hierarchy — essential for UI elements like modals, tooltips, and dropdowns that must break out of parent boundaries. In this tutorial, you'll learn how to build a powerful modal system using portals and hooks in a clean, scalable way.

Step 1: Create a Portal Target


Add a dedicated

in your HTML (typically inside public/index.html) for rendering portal content.



Step 2: Build a Modal Component Using createPortal


Use ReactDOM.createPortal to render the modal into the #modal-root.

import { useEffect } from "react";
import ReactDOM from "react-dom";

function Modal({ children, onClose }) {
useEffect(() => {
const handleEsc = (e) => e.key === "Escape" && onClose();
window.addEventListener("keydown", handleEsc);
return () => window.removeEventListener("keydown", handleEsc);
}, [onClose]);

return ReactDOM.createPortal(


e.stopPropagation()>
{children}

,
document.getElementById("modal-root")
);
}

Step 3: Use the Modal in Your App


You can now drop in modals anywhere without worrying about z-index, CSS overflow, or component nesting limitations.

import { useState } from "react";

function App() {
const [open, setOpen] = useState(false);

return (
<>

{open && (
setOpen(false)}>

This is a modal!


Click outside or press Escape to close.



)}
>
);
}

✅ Pros


  • Avoids z-index conflicts and CSS containment issues.
  • Great for modals, popovers, tooltips, or context menus.
  • Scales cleanly across apps without tight coupling.

⚠️ Cons


  • Requires manual DOM target setup.
  • Can complicate testing and debugging.
  • Accessibility (e.g., focus trap) needs extra handling.

Wrap-Up


React Portals are a must-have pattern for any advanced frontend project. With minimal boilerplate, you can render interactive components that feel truly native to modern UIs—without breaking layout or structure.

Ready to dive deeper now? Unlock the full potential of React Portals with my detailed 24-page PDF guide, available for just $10! You'll get step-by-step instructions on mastering everything from the basics to advanced portal techniques. Learn to create dynamic modals, optimize performance, handle nested portals, and ensure accessibility—all through real-world examples and best practices. This PDF is a must-have for any React developer looking to elevate their UI development skills. Don’t miss out on this essential resource—get your copy now for just $10 and start building more powerful and scalable React applications today!

If you enjoyed this, you can also support future dev-focused tutorials here: Buy Me a Coffee