Current section: Portals 36 exercises
lesson

Intro to Portals

Loading lesson

Transcript

00:00 All right, it's time to talk about portals. There's a video game about portals. I've never played it, but I think it's a good metaphor for what we're actually doing here. So there are use cases like dialogues and tool tips and popovers and things like that that need to be styled relative to the body of the body document.

00:18 So you need to insert DOM nodes in the body rather than in wherever component you're at. So like the component tree hierarchy and the DOM tree actually are like very, resemble each other very much. And so if you're like deep down doing something and you're like, I need to have a modal right here,

00:35 then that's gonna be tricky because the styling and everything is gonna mess that up. You actually need that DOM node to be all the way outside in the body. And if you do that, you can make that work with the use effect and stuff like that, but then you kind of lose the declarative stuff that we really enjoy out of React.

00:54 And so React has a special API called Create Portal that allows you to say, hey, I want this UI to be rendered in this location. Now we're gonna just stick this UI in the document.body. And of course, we're omitting a bunch of stuff for accessibility and things like that

01:11 to keep this example simple, but that's the idea. You create the portal, pass the UI you want, and then the element that you want it to be rendered into, and it will render the modal when it's supposed to, and when the modal gets removed, it will get removed for you automatically as well.

01:28 And so here we have a simple, click the button, show the modal, render the modal, and it all is happening inline. You still get your nice declarative experience that you have come to appreciate from React, and it works quite nicely. So this is gonna be a pretty quick one for this particular exercise, because there's not a whole lot

01:48 that you have to actually do. But it is an important thing for you to know and understand, and that's why we're gonna have you do it. Have fun.