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.
Let’s cut to the chase - here’s the source code for a component I’ve put together that you can add into your project more or less as-is. Quick caveat: I’m using typescript rather than plain javascript but I’m sure you can make any adjustments you need.
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.
Frontend web technologies are increasingly being used beyond traditional web applications. Could the next frontier be multi-window web apps that run in both the browser and on the desktop?
An introduction to our recently released open-source React Hooks library, OpenFin React Hooks. Developed especially for OpenFin and its developer community.
If you enjoyed this blog post, why not subscribe to our mailing list
to receive Scott Logic content, news and insights straight to your inbox?
Sign up here.