The Startup
Published in

The Startup

Everything You Need to Know About React Portals

Learn all about React portals and how to use them

React portals are a first-class method to render children into a DOM node that exists outside of the current parent. This is commonly used when you need a React component to visually “break out” of the current tree hierarchy. For example:

  • Dialogs
  • Modals
  • Tooltips

In all these cases, you’re rendering elements outside of the normal location in the DOM tree.

Photo by Christian Wiediger on Unsplash

Normally, when you return a component from the render method of a React component, it’s mounted in the DOM tree as the child of the nearest parent Node:

render() {
// React mounts a new div and renders the children into it
return (
<div> {this.props.children}
</div> );
}

We can use React portal to instead mount the component to a different location in the DOM:

render() {
// React does *not* create a new div. It renders the children into `domNode`.
// `domNode` is any valid DOM node, regardless of its location in the DOM.
return ReactDOM.createPortal(
this.props.children,
domNode
);
}

As seen above, you can create a portal using the ReactDOM.createPortal(child container) method, which takes two arguments, child , which is a React element, fragment, or string, and container , which is the DOM location where the portal is being injected.

For example, let’s see how we might implement a modal using this API.

const Modal =({ title, isOpen, onClose, children })=> {
if (!isOpen) return null
return ReactDOM.createPortal(
<div>
<h2>{title}</h2>
<button onClick={onClose}>Close</button>
</div>,
domNode) // The domNode is a reference to somewhere in a root component
}

Even though the portal is rendered outside of the parent DOM element, it behaves similarly to a normal React element. It can access the props and context API. This is because the portal doesn’t change the React tree hierarchy, just the rendered DOM hierarchy.

Things to keep in mind

There’s a couple key aspects of React portals that you need to keep in mind:

React has control over portals and their lifecycle

Even though the portal mounts in a different space in the DOM tree, React still has complete control over the lifecycle of the portal.

Your domNode needs to be predefined

Before using the React portal, you have to have your domNode defined as somewhere in your React tree.

Event bubbling works as usual

Events will bubble according to the React component tree, not the HTML DOM tree, and although portals modify the DOM tree, they don’t modify the component tree.

Make sure you manage keyboard focus

For users with screen readers or other assistive technology, React portals can be confusing, so managing keyboard focus is important. Read more about ARIA best-practices for modals here.

Conclusion

React portals can be really useful for creating modals, tooltips, and anything else where you need to render components somewhere else in the React tree. You can read more about React portals in the official documentation.

Keep in Touch

There’s a lot of content out there and I appreciate you reading mine. I’m an undergraduate student at UC Berkeley in the MET program and a young entrepreneur. I write about software development, startups, and failure (something I’m quite adept at). You can signup for my newsletter here or check out what I’m working on at my website.

Feel free to reach out and connect with me on Linkedin or Twitter, I love hearing from people who read my articles :)

--

--

--

Get smarter at building your thing. Follow to join The Startup’s +8 million monthly readers & +756K followers.

Recommended from Medium

Build your first Chatbot with Chatloop

How to deploy Vue.js website to Github Pages

Adding Groups, Roles and Permissions to a JWT access token in Auth0

Simple Item List Project with JavaScript DOM

The idea behind MVC a.k.a MVO

Cloning of DineOut with ReactJS

Callbacks vs. Promises in JavaScript

How to Scrape Government Data with JavaScript

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
Caelin Sutch

Caelin Sutch

Founder, engineer, designer. Passionate about building cool shit. On a break from UC Berkeley MET.

More from Medium

React Re-Reselect: Better Memoization and Cache Management

3 Popular React Interview Questions about Handling Props and State

How Jotai Specifies Package Entry Points

Implementing Google Fonts into your React project using Styled Components