Search code examples
javascriptreactjsace-editor

React - component or a way to have a console that is similar Chrome/Firefox JS console


I am working on React application that requires executing some JavaScript code in the browser. It has a code editor (using Ace editor), where user can type in some code, press Run button to execute the code and see the results output in some console.
What would be a good React "console" component or a way to build a console similar to Chrome/Firefox JS console ?


Solution

  • The most Naive way to do it is via the native eval() function in Javascript. I'm sure Ace provides some API to get the text in the editor. From there all you need to do is to tie an eval(*yourEditorText*) to your button and print it onto the screen.

    There are some caveats with that tho. Like if a user prints a for-loop that runs infinitely, your page is gonna crash. Security also becomes a concern. Read this to understand more about the effects of using eval() How can I make external code 'safe' to run? Just ban eval()?

    EDIT: If you want to print console messages on to the webpage, you have to do some weird stuff with hijacking the window.console object, to get the log messages and then pass it to your React object. Trying to work on a fiddle to do that.

    EDIT2: Made the fiddle: https://fiddle.jshell.net/julianljk/qsu5uzxk/