React Portals and event bubbling

Photo by Yong Chuan Tan on Unsplash

Portals can be a very handy tool in React. But you need to be careful about how you think about event bubbling.

Portals are a way of rendering children to a DOM node that exists outside the DOM hierarchy of the parent component. This is commonly used to allow child component’s to visually ‘break out’ of its container.

Since a portal can be anywhere in the DOM tree, it may seem that event propagation may occur separately. However, this is not the case.

The portal retains its position in the React tree, regardless of its actual position in the DOM tree. This means that events fired in a portal will propagate upwards to ancestors in the containing React tree, even if it is somewhere else in the DOM tree.

The fact that that the DOM tree is not equivalent to the React tree is obvious, in principle. But things can get a bit confusing with Portals since they purposefully place items within a React tree outside the normal flow of the DOM hierarchy.

I actually happened to chance on to this while helping debug a problem faced by a user of an internal component that I work on.

The user had our components composed in a way where a Portal based component with a link was nested within another component with a link. Normally, links within links do not work as they contravene HTML guidelines. However, here the user thought this rule would not apply since the use of a Portal meant that as far as the DOM was concerned these components were separate from each other.

But as we learnt above, the event propagation follows the React tree, thus the ‘no link in a link’ rule applies equally to links within Portals that are descendants of a component with a link.

In the example above, while it appears that the portalButton button within a portal is separate to the theComponent div, in the React tree theComponent is the ancestor. Thus the onClick event will event bubble up.

For more information about Portals and event propagation checkout the official React page on Portals.

--

--

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store
James Won

Software Engineer and history nerd from Wellington, New Zealand.