0

I have just started my front end web developer career and I have recently created my own blog. The blog is created using react. Now, I wanted to add a functionality where users can write and execute javascript code in my blog.

For example, they should be able to run console.log and get the output. Now, I don't know how to add that functionality. For example, should I need to learn node and add server side development for that or should I add server less functions??? How can I add that functionality??.

Note: I'm well versed with HTML and CSS that's why I have started the blog.

PS: Will it be costly to implement that??? Is there a cheaper option?

Coder6656
  • 21
  • 3
  • Does this answer your question? [How to safely run user-supplied Javascript code inside the browser?](https://stackoverflow.com/questions/22506026/how-to-safely-run-user-supplied-javascript-code-inside-the-browser) – Özgür Murat Sağdıçoğlu Aug 29 '22 at 05:52

1 Answers1

0

You will want to use a code editor package from npm

I have found this one Monaco and looks like what you are asking for.

Monaco image

You can find a full tutorial here

A basic implementation would look like:

import React, { useState } from "react";

import Editor from "@monaco-editor/react";

const CodeEditorWindow = ({ onChange, language, code, theme }) => {
  const [value, setValue] = useState(code || "");

  const handleEditorChange = (value) => {
    setValue(value);
    onChange("code", value);
  };

  return (
    <div className="overlay rounded-md overflow-hidden w-full h-full shadow-4xl">
      <Editor
        height="85vh"
        width={`100%`}
        language={language || "javascript"}
        value={value}
        theme={theme}
        defaultValue="// some comment"
        onChange={handleEditorChange}
      />
    </div>
  );
};
export default CodeEditorWindow;
Jonatan Kruszewski
  • 1,027
  • 3
  • 23