As part of a project I’m working on, I recently needed to open a new (non-modal) window to display some information to the user. If this was desktop development, which I’m generally more familiar with, this would be easy, but I didn’t think there was any way to do it in a single-page React app.
As it turns out, it’s actually very simple - as long as you’re using React v16 or higher.
React 16 introduced Portals. Whereas a typical React component renders its HTML as a child of its parent node, a component which uses a Portal allows you to render the HTML anywhere. You’d usually use this to create a floating tooltip or menu somewhere else in the DOM hierarchy, which is pretty clever in itself, but anywhere can also encompass a totally separate DOM - which is what we’re going to do here.
Your first question will probably be ‘How do I use this?’ I’ve got you covered. Here are the relevant bits of a component that uses the Popout component.
I imagine most of that is self-explanatory if you’ve worked with React before - it’s more or less just a state variable, a setter for it, and a render() method.
The two things I want to draw your attention to are:
The content for the popout window all lives in the component that controls the popout, and not in the Popout component itself.
Leading on from this, the owner component and the popout window share the same state. This is huge - you don’t need to do any work to sync anything.
It’s at about this point that the word ‘popout’ no longer looks like a real word to me.