UI/UX Design

What is a React Portal and how to use it

This feature was introduced in React 16 and the documentation states that:

Portals provide a first-class way to render children into a DOM node that exists outside the DOM hierarchy of the parent component.

React portals were created to be used in some situations like when a parent component has overflow: hidden for example and you don’t want to affect some of the children. One example would be a popup window nested in a container with a hidden overflow but you still want the popup to take the entire screen.

How to use?

React portals can be created by calling ReactDOM.createPortal. It only takes 2 arguments. The first argument should be a renderable child and the second argument should be a reference to the DOM node where you want the renderable child to be rendered. The ReactDOM.createPortal function will return an object.

  
  

render() {
  return ReactDOM.createPortal(
    [<p>Some JSX</p>],
    domNode,
  );
}

  

 

How to listen to events?

Listening to events inside the portals is as easy as if they were rendered in the same DOM tree as the parent component. The documentation states that:

Even though a portal can be anywhere in the DOM tree, it behaves like a normal React child in every other way. Features like context work exactly the same regardless of whether the child is a portal, as the portal still exists in the React tree regardless of its position in the DOM tree.
This includes event bubbling. An event fired from inside a portal will propagate to ancestors in the containing React tree, even if those elements are not ancestors in the DOM tree.

Conclusion

React Portals is a great feature which you can use when you run into overflow: hidden or stacking context issues. It is only available since React 16 and there are no special requirements for handling event bubbling.

Andy

UI/UX Designer & Front-end Engineer based in Dublin currently working @IBM.
I write about: UI/UX Design, Javascript, HTML, CSS, React JS and React Native

Add comment