Display Code Within An Iframe with React

Iframes, written in HTML as “<iframe>”, is a great resource for holding and displaying images. Anything from an intractable map pulled from an API or other HTML code itself to be render. This article will show you the latter, it gets pretty meta so let’s take a look.

Setting up iframe tag

First we will take look at the iframe and its attributes. There are many important ones but for the purpose of this article we will inspect the srcdoc attribute. The srcdoc is where we will store all our HTML code to be displayed in the iframe.

The srcdoc code looks very similar to html code and it displays the code just as we would imagine it would.

<iframe // iframe HTML tagsrcDoc="<BODY><h1>Hey</h1></BODY>"/> // Self-closing tag


There are many packages for javascript to accomplish this and they all follow the same concept, dynamically connecting the text from the editor with the srcdoc attribute in the iframe. We will use Ace Editor for React to take advantage of the component and some hooks

npm install react-ace ace-builds // install with node package manageryarn add react-ace ace-builds // install with yarn

then import ‘AceEditor’

import AceEditor from "react-ace";

AceEditor has some attributes we will focus on as well, the mode, the value and an onChange event.

mode // The language you wish your editor to write in
value // The value from the text editor, will be used in the srcdoc
onChange // Dynamically will update the iframe with our code

So here is our code now, notice we abstracted the srcdoc from within the iframe to variable outside the return so that we can better manipulate the value. We also added the useState hook and an onChange event to dynamically sync our editor with the iframe.

Connecting data

Our final step is to connecting the data from the editor and state to the srcdoc and iframe. We can also remove the srcdoc variable because our output is controlled by the useState.

Now we are free to type in the editor and see our results automatically display in the iframe. Have fun and experiment with the code and see what you can come up with.

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store