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 an iframe
. I have search through SO and Google as much as I know how, but haven't found anything useful, so I'm wondering if anyone has any tips or places that I should be looking into to get started trying to create an in-browser HTML compiler like this, preferably easily compatible with React/Next.js.
Thanks in advance!
CodePudding user response:
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
CodePudding user response:
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.