Portals in React
Expert-Level Explanation
Portals in React provide a way to render children into a DOM node that exists outside the DOM hierarchy of the parent component. This is particularly useful when you need to break out of the current HTML flow, such as when rendering modals, tooltips, or dialogues. A common use case is to render a modal dialogue that visually breaks out of its parent component but maintains all React behaviours like event handling and context.
Creative Explanation
Imagine you're painting a mural on a wall (a React component tree), but suddenly you need to paint part of it on a completely different wall, perhaps in another room (somewhere else in the DOM). Portals allow you to do this seamlessly. You can start painting on one wall and continue on another while still considering it part of the original artwork.
Practical Explanation with Code
Using Portals in React:
import React from 'react';
import ReactDOM from 'react-dom';
class MyModal extends React.Component {
render() {
return ReactDOM.createPortal(
this.props.children,
document.getElementById('modal-root')
);
}
}
// Usage
<MyModal>
<p>This is rendered in a modal!</p>
</MyModal>
In this example, MyModal
uses ReactDOM.createPortal
to render its children into a DOM node identified by'modal-root', which is typically located outside the main app's DOM hierarchy.
Real-World Example
In a web application like an online store, portals can be used for rendering product zoom modals. When a user clicks on a product image, a full-screen modal with the zoomed-in image opens up, rendered using a portal, so it overlays the rest of the page content.
Subscribe to my newsletter
Read articles from Akash Thoriya directly inside your inbox. Subscribe to the newsletter, and don't miss out.
Written by
Akash Thoriya
Akash Thoriya
As a senior full-stack developer, I am passionate about creating efficient and scalable web applications that enhance the user experience. My expertise in React, Redux, NodeJS, and Laravel has enabled me to lead cross-functional teams and deliver projects that consistently exceed client expectations.