Building a Live Editor
Published ....
Last modified ....
Share this post on BlueskySee discussion on Bluesky
As I have been working on my personal blog, I wanted to include the ability to edit code on site, and also preview it live. I started using react-live which I have had prior experience using and setting up, however I wanted to customize the theme of the editor a bit and try to work on a new and challenging task over the weekend.
So I decided to build @matthamlin/react-preview-editor
(see the project here).
Starting Off with Executing Code
I started off by looking at the source of react-live to figure out how they are
able to actually call the code that you edit inline. It turns out, that they use
the new Function contructor to pass the code as a string along with an
assortment of the keys of the things within scope for the code, and then call
the function.
function evaluateCode(code, scope) {
// scope looks like this: { variableName: 'value' }
// construct a new function with the code