React Portals
Learn how to use React Portals to render components outside of their parent DOM hierarchy.
1. What are React Portals?
React Portals provide a way to render children into a DOM node that exists outside the DOM hierarchy of the parent component.
- Separate DOM Tree: Components can be rendered into a completely different part of the DOM.
- Useful for Modals and Tooltips: Ideal for UI elements that need to break out of the usual DOM structure.
2. How to Create a Portal
The ReactDOM.createPortal
method is used to create a portal.
import React from 'react'; import ReactDOM from 'react-dom'; function Modal({ children }) { return ReactDOM.createPortal({children}, document.getElementById('modal-root') ); } export default Modal;
Explanation: The above code renders the Modal
component inside the DOM element with the ID modal-root
.
3. Setting Up the DOM Structure
Ensure the HTML includes a dedicated element for the portal:
React App
Note: The root
element is for the main React app, while modal-root
is for portals.
4. Using Portals for Modals
Here’s an example of using a portal for a modal component:
import React, { useState } from 'react'; import Modal from './Modal'; function App() { const [showModal, setShowModal] = useState(false); return (); } export default App;Welcome to the Portal Example
{showModal && ()} Modal Content
Explanation: Clicking the button toggles the modal, which is rendered in a separate DOM node using a portal.
5. Styling Portals
To style the portal’s content, use CSS targeting the modal
and modal-content
classes:
.modal { position: fixed; top: 0; left: 0; width: 100%; height: 100%; background: rgba(0, 0, 0, 0.5); display: flex; justify-content: center; align-items: center; } .modal-content { background: white; padding: 20px; border-radius: 10px; text-align: center; }
Explanation: The modal is styled to cover the entire screen and display its content in the center.
6. Best Practices
- Ensure that the portal's content is accessible (e.g., use
aria-hidden
attributes). - Use portals for UI elements that need to escape the parent DOM hierarchy.
- Clean up portal elements when they are no longer needed to prevent memory leaks.