React · Lesson 74 of 120
Portals
Modals.
Modals and tooltips must appear above everything else. But a parent with hidden overflow can clip them. A portal renders a component somewhere else in the page, while it still belongs to its React parent.
- Above everything
- Clipped by parents
- Render elsewhere
A delivery modal
A portal renders children into a different place in the page, here the document body. The modal is written inside App, but appears outside its box. So the box's hidden overflow can't clip it. Events still bubble up through React, as if it were inside. We open the modal. Run it.
App.jsxjsx
import { useState } from "react";
import { createPortal } from "react-dom";
function Modal({ onClose, children }) {
return createPortal(
<div style={{ position: "fixed", inset: 0, background: "#0008", display: "grid", placeItems: "center" }}>
<div className="box">{children} <button id="close" onClick={onClose}>Close</button></div>
</div>,
document.body
);
}
export default function App() {
const [open, setOpen] = useState(false);
return (
<div className="box" style={{ overflow: "hidden", height: 80 }}>
<button id="open" onClick={() => setOpen(true)}>Delivery info</button>
{open && <Modal onClose={() => setOpen(false)}>Free delivery over £500.</Modal>}
</div>
);
}Also uses style.css
body{font-family:-apple-system,Helvetica,Arial,sans-serif;margin:22px;font-size:21px;color:#1d1d1f;background:#fafafa}
h1{font-size:34px;margin:0 0 14px} h2{font-size:26px;margin:0 0 10px}
button{font-size:19px;padding:9px 18px;border-radius:9px;border:0;background:#61dafb;color:#111;font-weight:600;margin:4px 6px 4px 0}
input{font-size:19px;padding:8px 10px;border:2px solid #bbb;border-radius:8px}
li{margin:5px 0} .box{padding:14px;border-radius:12px;background:#fff;border:2px solid #ddd;margin:8px 0}
.done{text-decoration:line-through;color:#999} small{color:crimson;display:block;font-size:16px} .big{font-size:64px;font-weight:800}Also uses actions.json
[{"click": "#open"}]Summary
Create portal renders a component elsewhere in the page, perfect for modals. Next, the advanced quiz.
Key takeaways- createPortal
- document.body
- Still React
Next up: Advanced Quiz — test yourself