REACT Portals

A React Portal allows you to render components outside the normal DOM hierarchy, typically into a different DOM node.

How to Use React Portals

1. Create a New React App

If you don’t have a React app yet, create one:

npx create-react-app react-portals-demo
cd react-portals-demo
npm start

Try It Now

2. Create a Portal Root in public/index.html

Find index.html inside the public folder and add a new div inside <body>:

<div id="modal-root"></div>

Try It Now

This is where our modal will be rendered using React Portal.

3. Create a Modal Component (src/Modal.js)

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

const Modal = ({ children, onClose }) => {
  return ReactDOM.createPortal(
    <div style={modalStyles}>
      <div style={modalContentStyles}>
        <button onClick={onClose} style={closeButtonStyles}>❌ Close</button>
        {children}
      </div>
    </div>,
    document.getElementById("modal-root") // This renders inside the portal
  );
};

const modalStyles = {
  position: "fixed",
  top: 0,
  left: 0,
  width: "100%",
  height: "100%",
  backgroundColor: "rgba(0, 0, 0, 0.5)",
  display: "flex",
  justifyContent: "center",
  alignItems: "center",
};

const modalContentStyles = {
  background: "#fff",
  padding: "20px",
  borderRadius: "10px",
  boxShadow: "0px 0px 10px rgba(0,0,0,0.25)",
  textAlign: "center",
};

const closeButtonStyles = {
  position: "absolute",
  right: "10px",
  top: "10px",
  border: "none",
  background: "red",
  color: "white",
  padding: "5px",
  cursor: "pointer",
};

export default Modal;

Try It Now

4. Use the Portal in src/App.js

Replace the content of src/App.js:

import React, { useState } from "react";
import Modal from "./Modal";

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

  return (
    <div style={{ textAlign: "center", marginTop: "50px" }}>
      <h1>⚡ React Portals Demo</h1>
      <button onClick={() => setIsModalOpen(true)}>Open Modal</button>

      {isModalOpen && (
        <Modal onClose={() => setIsModalOpen(false)}>
          <h2>This is a Portal Modal! 🎉</h2>
          <p>It renders outside the main component tree.</p>
        </Modal>
      )}
    </div>
  );
}

export default App;

Try It Now

 

Why Use React Portals?

Modals won’t be affected by parent CSS (overflow, z-index, etc.)
Prevents unwanted scrolling issues
More control over rendering in the DOM