A Comprehensive Guide to Harness the Potential of React Portals

React Portals, as we speak, were introduced in React v16 and provide an optimum way to render and permit the child components (typically present outside the DOM) to exist within a Document Object Model(DOM) node. The specific portal component exists outside the DOM hierarchy of the parent component. We will cover the following points, giving us a much deeper understanding of React Portals.

Key Takeaways

  1. Introduction to React Portal
  2. Why do we need to use Portals?
  3. Implementing React Portal
  4. Points to remember while using portals
  5. Key benefits and Use cases of React Portals
  6. Conclusion

Introduction to React Portal

As mentioned before, we use React Portal to render our child components into a DOM that generally resides outside of the parent DOM. Prior to React v16, it was challenging and complex to render the child components outside the parent component as it would break the convention in which the component needs to be rendered as a new element and follow the parent-child hierarchy.

The portal can be used as a modal dialog box, loader, hover cards, or tooltip to create the child component, each time the child component breaks out from the parent.
In order to create a React Portal, we use the following syntax:-

ReactDOM.createPortal(child, container)

Here “child” indicates a React element, string, or fragment, and the “container” signifies the DOM node to which the portal should be linked to.
Consider the following sample modal component as an example:-

const Modal =({ message, isOpen, onClose, children })=> {
if (!isOpen) return null
return ReactDOM.createPortal( 
<div className="sample-modal">
<span className="message-text">{message}</span>
 <button onClick={onClose}>Close</button>
</div>,
domNode)
}

Why do We Need to Use Portals?

When a modal is used inside the parent component, the width and height of the modal are inherited from the parent component in which it resides, and there is a probability that the modal will not be shown properly and will be cropped out.
In order to get through this, a traditional modal would make use of

overflow: hidden

and

z-index.

Consider the following example:-

const Component = () => {
const [open, setOpen] = useState(false)
return (
<div className="component">
<button onClick={() => setOpen(true)}>Open Modal</button>
<Modal
message="Hello World!"
isOpen={open}
onClose={() => setOpen(false)}
/>
</div>
)
}

When we inspect the app inside the browser, it displays that the modal has been rendered inside the nested components under the “div” tag having id of “root” and is inheriting the width and height of the parent component.

We can make use of the traditional CSS properties to get around this issue, but a much more dynamic and suggested approach would be to make use of Portals.

Check Out what it Takes to Build a Successful App here

Implementing React Portal

The issue discussed in the previous point can be resolved using “createPortal()” method to create a DOM node outside the hierarchy of the root tree. Let us consider and make changes in the previous example only:-

const Modal =({ message, isOpen, onClose, children })=> {
if (!isOpen) return null;
return ReactDOM.createPortal(
<div className="modal">
<span>{message}</span>
<button onClick={onClose}>Close</button>
</div>
,document.body);
}

const Component = () => {
const [open, setOpen] = useState(false)
return (
<div className="component">
<button onClick={() => setOpen(true)}>Open Modal</button>
<Modal
message="Hello World!"
isOpen={open}
onClose={() => setOpen(false)}
/>
</div>
)
}

As clearly visible in the above figure, the modal is present inside the DOM hierarchy. Still, it is injected outside of the “div” element having the id of “root”. The modal makes use of the “createPortal()” method and doesn’t inherit the dimensions of the parent component but will have all the advantages of a React component.

Points to Remember While Using Portals

  • Effect on DOM Structure:- When using portals, the HTML structure only gets affected and has no impact on the React components tree.
  • Control over Portal nodes:- Even when the child elements are rendered through portals, React still has complete control over their lifecycle.
  • Event Bubbling through portals:- As per this phenomenon, even though a Portal can reside anywhere inside the DOM tree, an event fired from within the portal. would propagate the ancestor into holding the react tree even if those elements are not the ancestors inside the DOM.

Key Benefits and Use Cases of React Portals

  • Portals make use of context to transfer data.
  • Another benefit includes event-bubbling under which the portal(which lies outside the DOM tree) can communicate with the parent component, present inside the DOM tree.
  • Helps in keeping parent components focused on state and behavior, while portal components handle rendering.
  • Optimize rendering by bypassing unnecessary updates and reducing component tree size.
  • Simplified testing and debugging of portal components.
  • Better control over the stacking order of elements.

Common use cases include:-

  • Modal Dialog Box: Enhancing User Interaction with Dynamic Content Display.
  • Loaders: Engaging Visual Elements for Seamless User Experience.
  • Hover Cards: Interactive Components for Enhanced User Interaction.
  • Tooltips: Contextual Information at Your Fingertips for Better User Experience.
coma

Conclusion

Through this blog, we understood the importance of React Portals and how they come in handy when there is a need to render child components outside the DOM hierarchy without using the traditional CSS properties and breaking React tree component hierarchy. Along with that, we also understood it’s working through an example and the points which need to be aware of when working with portals.

Keep Reading

  • Service
  • Career
  • Let's create something together!

  • We’re looking for the best. Are you in?