createPortal(children, domNode, key?)
children
: Anything that can be rendered with React, such as a piece of JSX (e.g. <div />
or <SomeComponent />
), a Fragment (<>...</>
), a string or a number, or an array of these.
domNode
: Some DOM node, such as those returned by document.getElementById()
. The node must already exist. Passing a different DOM node during an update will cause the portal content to be recreated.
optional key
: A unique string or number to be used as the portal’s key.
// App.js
import NoPortalExample from './NoPortalExample';
import PortalExample from './PortalExample';
export default function App() {
return (
<>
<div className="clipping-container">
<NoPortalExample />
</div>
<div className="clipping-container">
<PortalExample />
</div>
</>
);
}
// PortalExample.js
import { useState } from 'react';
import { createPortal } from 'react-dom';
import ModalContent from './ModalContent.js';
export default function PortalExample() {
const [showModal, setShowModal] = useState(false);
return (
<>
<button onClick={() => setShowModal(true)}>
Show modal using a portal
</button>
{showModal && createPortal(
<ModalContent onClose={() => setShowModal(false)} />,
document.body
)}
</>
);
}
// ModalContent.js
export default function ModalContent({ onClose }) {
return (
<div className="modal">
<div>I'm a modal dialog</div>
<button onClick={onClose}>Close</button>
</div>
);
}