How to make iframes persistent in React, Vue, Svelte et al

How to make iframes persistent in React, Vue, Svelte et al
Photo by Andrew Neel / Unsplash

One of the most annoying things while working with iframes in reactive UI libraries like React, Vue or Svelte, is that it's very easy to accidentally make your iframes unstable in them. If you put an iframe behind a conditionally rendering component like a tab or a checklist, it also reloads the iframe every time.

Every time you click on the checkbox "Show Iframe", it will reload the related iframe. This is because of a very simple reason. Can you find out what it is?

Believe it or not, this behavior is intentional, as your UI library follows a standard practice of removing the component's code from the Document Object Model (DOM) every time it is unmounted. In the world of reactive UI libraries, components have a lifecycle that includes a 'mount' phase when they are first rendered and an 'unmount' phase when they are removed.

During the unmount phase, the component's code, along with any associated elements like iframes, is completely taken out of the DOM. Subsequently, when the component is mounted again, the library adds the code back into the DOM, leading to the observed reloading of iframes. This process ensures a clean and consistent state for components, but it can inadvertently cause iframes to reload as they are tied to the lifecycle of the enclosing component.

Here's the offending line from the code.

{showIframe ? (
  <iframe ...></iframe>
) : (

There's a cheeky way to fix this. Instead of unmounting the iframe when the checkbox is unchecked, we can instead have it load in the background and set the display property to none instead. Here's how it works below.

And that, is how we persist iframes in reactive languages.