React Portals provide a way to render components outside the main DOM hierarchy. This is especially useful for creating modals, tooltips, and popovers that need to break free of their parent components’ CSS constraints or z-index stacking contexts.
What Are React Portals?
Portals allow React to render elements in a different part of the DOM tree than the rest of the app. They can help you avoid CSS issues and improve accessibility for UI elements like modals.
How to Use Portals?
- Create the Portal Target: Add an element with an ID in your HTML (e.g.,
<div id="portal-root"></div>
). - Render in the Portal: Use
ReactDOM.createPortal
to render components into that element.
Let’s look a quick example:
import ReactDOM from 'react-dom';
const Modal = ({ isOpen, onClose, children }) => {
if (!isOpen) return null;
return ReactDOM.createPortal(
<div className="modal-backdrop">
<div className="modal">
<button onClick={onClose}>Close</button>
{children}
</div>
</div>,
document.getElementById('portal-root')
);
};
export default Modal;
And this is how we would use it:
import { useState } from 'react';
import Modal from './Modal';
const App = () => {
const [isModalOpen, setModalOpen] = useState(false);
return (
<div>
<button onClick={() => setModalOpen(true)}>Open Modal</button>
<Modal isOpen={isModalOpen} onClose={() => setModalOpen(false)}>
<p>This is a portal modal!</p>
</Modal>
</div>
);
};
Benefits and Use Cases for Portals
Portals make it easy to build:
- Modals that aren’t restricted by the main app’s styling.
- Tooltips and Popovers that can escape overflow and z-index issues.
- Notifications and Toasts that appear at a global level.
Conclusion
React Portals are an excellent solution for components that need to render outside their parent DOM tree. They’re particularly helpful for building UI elements that require isolation from parent components’ styling constraints.
Web developer with over ~6 years of experience. I am a highly motivated and results-oriented developer with a passion for creating scalable and user-friendly web applications. I am recently exploring the world of blogging, hoping to share some of my experience in this exciting and ever-evolving journey of development.