18React Portals

ReactDOM.render renders a React application in a single DOM node in a web page. But it may be a big document outside that node, and there are times when your application may need access to that larger world. React Portals provide you with a way to access and control DOM nodes beyond the root in which it’s rendered.

In this chapter, you'll learn:

  • How to create a Portal.
  • Common use cases for Portals.
  • How to make a modal dialog with Portals.
  • How to listen for and handle events within Portals.
  • How to properly handle keyboard focus with Portals.

WHAT IS A PORTAL?

A Portal is a way to render child components into different DOM nodes than the root of your React application. For example, if you have a modal dialog box that appears when the user clicks a help link, a Portal lets you render that dialog box in a separate element in the HTML that's styled to appear on top of the React application, as shown in Figure 18-1.

How to Make a Portal

Because Portals interact with the DOM, they're a part of the ReactDOM library. To create a Portal, use the ReactDOM.createPortal method within a React component. ReactDOM.createPortal works the same way as ReactDOM.render, except that it works inside a React component's render method. Like ReactDOM.render, it takes two arguments: the component to render and the DOM node in which to render it.

Snapshot shows Portals enable modal dialogs

FIGURE 18-1: Portals enable modal ...

Get Beginning ReactJS Foundations Building User Interfaces with ReactJS now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.