React Portals provide a way to render children into a DOM node that exists outside the hierarchy of the parent component. This allows you to render components in a different part of the DOM, which can be useful for scenarios like modals, tooltips, or any situation where you need to render content outside the normal React component tree.
Here's a basic example of using React Portals:
import React, { useState } from 'react';
import ReactDOM from 'react-dom';
const Modal = ({ isOpen, onClose, children }) => {
if (!isOpen) return null;
return ReactDOM.createPortal(
<div className="modal-overlay">
<div className="modal">
<button onClick={onClose}>Close</button>
{children}
</div>
</div>,
document.body // Render the modal outside the parent component's DOM hierarchy
);
};
const App = () => {
const [modalIsOpen, setModalIsOpen] = useState(false);
return (
<div>
<h1>Hello, React Portals!</h1>
<button onClick={() => setModalIsOpen(true)}>Open Modal</button>
<Modal isOpen={modalIsOpen} onClose={() => setModalIsOpen(false)}>
<p>This is the content of the modal.</p>
</Modal>
</div>
);
};
ReactDOM.render(<App />, document.getElementById('root'));
In this example:
-
The
Modalcomponent renders its content inside adivwith the classmodal-overlay. The entire modal is then rendered inside adivwith the classmodal. TheModalcomponent usesReactDOM.createPortalto render its content outside the normal component hierarchy. -
The
Appcomponent includes a button to open the modal. TheModalcomponent is conditionally rendered based on themodalIsOpenstate. -
The
Modalcomponent is appended to thedocument.body, ensuring that it is rendered outside the normal React component tree.

Comments