React portals
Created By: chatGPT
React Portals provide a way to render children into a DOM node that exists outside of the DOM hierarchy of the parent component. This is particularly useful for modals, tooltips, and popovers, where you might want to escape the overflow or z-index constraints of parent components. Here’s how to use portals in React.
import React from 'react';
import ReactDOM from 'react-dom';
function Modal({ children, onClose }) {
return ReactDOM.createPortal(
<div className="modal">
<div className="modal-content">
<button onClick={onClose}>Close</button>
{children}
</div>
</div>,
document.getElementById('modal-root') // The DOM node to render into
);
}
export default Modal;
First, create a DOM node in your
index.html
file that will serve as the target for the portal. This node is typically outside of your React application’s root.<div id="modal-root"></div>
Next, you can use the Modal component in your main application. Use state to handle its visibility.
import React, { useState } from 'react';
import Modal from './Modal';
function App() {
const [isModalOpen, setModalOpen] = useState(false);
const openModal = () => setModalOpen(true);
const closeModal = () => setModalOpen(false);
return (
<div>
<button onClick={openModal}>Open Modal</button>
{isModalOpen && <Modal onClose={closeModal}>This is a modal!</Modal>}
</div>
);
}
export default App;
Now, when the Open Modal button is clicked, the modal will render outside of the standard React DOM tree into the
modal-root
div, allowing for flexible positioning and styling without being constrained by parent components.<div style="position: relative; z-index: 999;">My App Content</div>