React Portals

A presentation at Web Dev Weekly in May 2018 in by Andrew Smith

Slide 1

Slide 1

React Portals

Slide 2

Slide 2

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

Slide 3

Slide 3

Slide 4

Slide 4

Slide 5

Slide 5

React Portals can render content outside of our main application

Slide 6

Slide 6

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

Slide 7

Slide 7

Modal dialogs Hovercards Tooltips Cookie Bars Save to HomeScreen

Slide 8

Slide 8

Using Portals

Slide 9

Slide 9

Slide 10

Slide 10

Slide 11

Slide 11

Slide 12

Slide 12

Slide 13

Slide 13

Slide 14

Slide 14

Slide 15

Slide 15

Slide 16

Slide 16

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

Slide 17

Slide 17

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

  • any React child container
  • DOM element

Slide 18

Slide 18

HTML JavaScript

Slide 19

Slide 19

Modal Component

Slide 20

Slide 20

Parent Component

Slide 21

Slide 21

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

Slide 22

Slide 22

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

Slide 23

Slide 23

Document Object Model ↓

React Tree

Slide 24

Slide 24

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.

Slide 25

Slide 25

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

Slide 26

Slide 26

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

(don’t do this)

Slide 27

Slide 27