hardFrontend

What are Portals in React and when would you use them?

888 views
01

Understand the problem

Describe React Portals and identify scenarios where they are particularly useful.

portalsdomuiadvanced
02

Attempt it yourself

Sketch your approach before reading the solution — that's what interviews test.

Stuck? AI Nudge Available

Get a conceptual hint to guide your logic without spoiling the final implementation.

03

Study the solution

The solution is waiting

Give it an honest attempt first — then compare your thinking with the full walkthrough.

04

Read the code

A modal via createPortal
import { useState } from "react";
import { createPortal } from "react-dom";

function Modal({ onClose, children }) {
  return createPortal(
    <div style={{ position: "fixed", inset: 0, background: "rgba(0,0,0,.5)" }}
         onClick={onClose}>
      <div style={{ background: "#fff", margin: "10% auto", padding: 24, width: 280 }}>
        {children}
      </div>
    </div>,
    document.body                       // rendered here, not in the parent DOM
  );
}

export default function App() {
  const [open, setOpen] = useState(false);
  return (
    <div style={{ padding: 24, fontFamily: "system-ui", overflow: "hidden" }}>
      <button onClick={() => setOpen(true)}>Open modal</button>
      {open && <Modal onClose={() => setOpen(false)}>Hi from a portal!</Modal>}
    </div>
  );
}
05

Join the discussion

Discussion (0)

Sign in to join the discussion.

No responses yet. Be the first to share what you think.