What Are React Portals? Complete Example Tutorial Guide

What Are React Portals?

React Portals allow you to render components outside the main DOM hierarchy of the parent component.
This is useful for modals, tooltips, and overlays.


Basic Syntax

ReactDOM.createPortal(child, container)
  • child → React element to render
  • container → DOM node to render into

Example: Modal Using Portal

import React from "react";
import ReactDOM from "react-dom";

function Modal({ children }) {
  return ReactDOM.createPortal(
    <div className="modal">{children}</div>,
    document.getElementById("modal-root")
  );
}

function App() {
  return (
    <div>
      <h1>My App</h1>
      <Modal>
        <p>This is a portal modal!</p>
      </Modal>
    </div>
  );
}

Key Points

  • Renders outside parent DOM tree
  • Useful for modals, tooltips, popups
  • Still part of React component hierarchy
  • Can access props, state, and context normally

Conclusion

React Portals help render UI elements outside parent hierarchy, improving flexibility for overlays and modals while keeping React logic intact.


Citations

https://savanka.com/category/learn/react/
https://www.w3schools.com/REACT/DEFAULT.ASP

Leave a Comment

Comments

No comments yet. Why don’t you start the discussion?

Leave a Reply

Your email address will not be published. Required fields are marked *