React Portals

What are React Portals? Why are they useful? How do you use them? Let’s have some cake.

React Portals can render content outside of our main application

Typical use case: When a parent component has overflow: hidden or z-index   style but the child needs to “break out” of its container.

Modal dialogs Hovercards Tooltips Cookie Bars Save to HomeScreen

Using Portals

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

ReactDOM.createPortal Syntax ReactDOM.createPortal(child, container); child

  • any React child container
  • DOM element

HTML JavaScript

Modal Component

Parent Component

https://codepen.io/andismith/pen/xjjKrW

Structure & design can be contained within the component calling it Props & state shared

Document Object Model ↓

React Tree

Event Bubbling Through Portals Because the portal exists in the React tree, you can use all the same features you’d use in the DOM. Like event bubbling. Trigger a click in the modal, catch it in the component.

https://codepen.io/andismith/pen/rvvMGa

Go crazy with the idea and open up a portal in a new window! https://codepen.io/davidgilbertson/ pen/xPVMqp

(don’t do this)