0

I'm working on a piece of my Next.js app, and I'd love to create a section that allows for users to write simple HTML and CSS and compiles the results, displaying them in browser. Similar to the editor pages on W3.

I don't have much to go on in terms of what I've tried, as this is a completely new concept for me, but from the little I've seen in other similar tools, you can compile the code into a Blob() and then set that Blob() as the src for a iframe.

How to create an in-browser HTML compiler like this, preferably easily compatible with React/Next.js?

Dharman
  • 30,962
  • 25
  • 85
  • 135
Jesse Winton
  • 568
  • 10
  • 33
  • If you want to compile HTML/CSS/Javascript simply, you can easily create an iframe with "srcdoc" attribute with your desired content directly. – Zafar Kamal May 22 '22 at 18:23

3 Answers3

2

You can accomplish that using an iframe and textarea. textarea will be used as an editor and iframe as a sandbox to see the result.

const Sandbox = () => {
  const textareaRef = useRef(null);
  const [code, setCode] = useState("");

  const runCode = () => setCode(textAreaRef.current.value);

  return (
    <div className="App">
      <div>
        <textarea ref={textareaRef}></textarea>
        <button onClick={runCode}>Run</button>
      </div>
      <iframe
        src={"data:text/html," + encodeURIComponent(code)}
        title="sandbox"
      />
    </div>
  );
  
}

here we create a ref to access to textarea content, and a button to run user's entered snippet. then pass that code to an iframe using src attribute and after that it will render the entered code like an existing HTMl page. look at here for more info on how it works.

see the working example on codesandbox

Mohammad Reza
  • 361
  • 3
  • 10
-1

You can use ref attribute to get content from a textarea. To render the content you can define the srcdoc of an iframe with respective content.

Since you are asking for a place to start, here is a simple tutorial that creates an html/css/js editor with react: https://www.youtube.com/watch?v=wcVxX7lu2d4

Also I found this article useful: https://medium.com/@nishantsaxena269/html-editor-using-react-98e6ab2183a5

besjon_c
  • 170
  • 2
  • 12
-1

If you want to render html input in react you can do that with this below

const App = () => {
  const data = 'lorem <b>ipsum</b>';

  return (
    <div
      dangerouslySetInnerHTML={{__html: data}}
    />
  );
}

export default App;

This will render any html you type.