What Are React Portals? Complete Example Tutorial Guide

What Are React Portals?

React Portals allow you to render a component outside the parent DOM hierarchy while maintaining the React tree.
Useful for modals, tooltips, or overlays.


Basic Syntax

ReactDOM.createPortal(child, container)
  • child → the component to render
  • container → DOM element outside the parent hierarchy

Example: Modal Using Portal

import React, { useState } from "react";
import ReactDOM from "react-dom";

function Modal({ children }) {
  return ReactDOM.createPortal(
    <div style={{ position: "fixed", top: 0, left: 0, background: "rgba(0,0,0,0.5)", width: "100%", height: "100%" }}>
      {children}
    </div>,
    document.getElementById("modal-root")
  );
}

function App() {
  const [show, setShow] = useState(false);

  return (
    <div>
      <button onClick={() => setShow(true)}>Open Modal</button>
      {show && <Modal><h2>Modal Content</h2><button onClick={() => setShow(false)}>Close</button></Modal>}
    </div>
  );
}

export default App;

✅ Modal renders outside the main DOM hierarchy but remains part of React tree.


Key Points

  • Useful for modals, tooltips, overlays
  • Maintains React tree integrity
  • Renders outside parent DOM node
  • Works with any child component

Conclusion

React Portals allow flexible component rendering outside the parent DOM hierarchy while preserving React functionality.


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 *