Skip to content
On this page

Editing a file and updating the iframe

Your Express app is up and running in WebContainers, but if you edit the textarea, the changes are not reflected in the Preview window at all. Let's change that.

1. Create a function to write a file

To change the contents of a file, you will use the fs.writeFile method.

In this case, you're editing only index.js so the function will be quite concise.

js
/** @param {string} content*/

async function writeIndexJS(content) {
  await webcontainerInstance.fs.writeFile('/index.js', content);
};

2. Listen to textarea changes

Now that you have a function to write the file, you can listen to textarea value change and call this function. To do so, attach the input event listener to the textareaEl:

js
window.addEventListener('load', async () => {
  textareaEl.value = files['index.js'].file.contents;

  textareaEl.addEventListener('input', (e) => {
    writeIndexJS(e.currentTarget.value);
  });
});

Try changing the emoji now.

An app with a textarea showing express js index.js code on left, and its output on right side using an iframe

And voilĂ ! We have a working editor with the Preview. You've built your own environment!

Next steps

If you'd like to explore the API on your own, you can check out the API reference or see the projects made by our Community.

Was this page helpful?