>React createPortal
React.createPortal is a method provided by React to render components outside the DOM hierarchy of their parent component. It allows you to mount a child node into a different part of the DOM, independent of where it is declared in your React component tree.
Why Use createPortal?
Portals are particularly useful when you need to render elements that should visually break out of their parent container or work independently of its styling or positioning.
Common Use Cases
- Modals and Dialog Boxes Modals often need to overlay the entire screen and not be constrained by the styles of their parent container.
- Tooltips Tooltips need to appear on top of other elements, even when triggered from within deeply nested components.
- Dropdown Menus Like tooltips, dropdown menus often need to appear outside of their parent's overflow constraints.
- Notification Toasts Toast notifications are typically placed at a fixed position on the screen, independent of the current DOM structure.
- Global Elements Some global elements like contextual menus or floating action buttons need to be rendered at specific places in the DOM, such as a body tag.
Example :
import React, { useState } from "react";
import ReactDOM from "react-dom";
const App = () => {
const [showModal, setShowModal] = useState(false);
return (
<div>
<h1>React Portals Demo</h1>
<button onClick={()=> setShowModal(true)}>Open Modal</button>
{showModal && (
<Modal onClose={()=> setShowModal(false)}>
<h2>This is a modal</h2>
<button onClick={()=> setShowModal(false)}>Close</button>
</Modal>
)}
</div>
);
};
const Modal = ({ children, onClose }) => {
return ReactDOM.createPortal(
<div>
{children}
<button onClick={onClose}>Close Modal</button>
</div>,
document.getElementById("modal-root")
);
};
export default App;