Search code examples
reactjsiframerendervirtual-dom

React internals: How does React know how to rerender an iframe correctly?


I was experimenting with React and rerendering iframes and I was not sure how React correctly rerenders iframes, especially ones which point to a text editor. Here is a jsFiddle showing this:

https://jsfiddle.net/augburto/fkqnm329/2/

The text editor I point to is not important but what I am doing is when you click Trigger Update, it will call a setInterval which will constantly set a new state and thus trigger a rerender.

What I thought might happen is that when I'm typing in the iframe which has a textarea, it will inevitably rerender and thus make me lose my text editor position but somehow I am able to type seamlessly without any issues despite seeing the rerenders come through in the console.log. Note I'm not suggesting it should do this -- I'm just wondering why it doesn't do that. I know React internals do some smart things like transactions but I wouldn't expect it to maintain my cursor position or what I have selected.

So how does React handle rerendering iframes more specifically? I have read articles (i.e. this and this but they don't shed a lot of light on it I feel). Is it any different from regular DOM elements?


Solution

  • Okay so after some time, I think I believe I discovered the answer. In general, because React just creates a virtual DOM and does a diff behind the scenes, it really is only looking at the iframe element and not what is generated. That is a completely separate thing where the iframe creates its own browsing context. Reading the MDN documentation on iframe was really informative:

    The HTML element represents a nested browsing context, effectively embedding another HTML page into the current page. In HTML 4.01, a document may contain a head and a body or a head and a frameset, but not both a body and a frameset. However, an can be used within a normal document body. Each browsing context has its own session history and active document. The browsing context that contains the embedded content is called the parent browsing context. The top-level browsing context (which has no parent) is typically the browser window.

    I think React does do some special things when it comes to parsing an iframe but overall it doesn't deviate too much in general.

    Also something that I think might be informative is how React handles input elements in general -- take a look at Controlled Components in general for Forms as React has a completely separate and special way of handling those cases.