I would like to create a small and minimal code editor (in Javascript) to use React Js. I’m creating the code editor from scratch. I will need the code editor for educational reasons, only for simple online exercises in a free course site.
I would like to get this like w3schools. I created a code editor that reads html, css and js code, but of course it doesn’t read React code. I would like to try to view the Previews of a simple only Hello World!
(without import, function, etc.). How can I make my code editor read React code? I know, I could use ready-made code editors, but I would like to try to create one from scratch considering that i only need them for teaching exercises in a free course site.
html
<div id="htmlCode" contenteditable="true" oninput="showPreview()">import React from "react";
import ReactDOM from "react-dom/client";
function Hello(props) {
return <h1>Hello World!</h1>;
}
const container = document.getElementById('root');
const root = ReactDOM.createRoot(container);
root.render(<Hello />);
</div>
<h3>PREVIEW</h3>
<div class="preview-area">
<iframe id="preview-window"></iframe>
</div>
css
#htmlCode {
width: 456px;
height: 165px;
padding: 10px;
background-color: #444;
color: white;
font-size: 14px;
font-family: monospace;
white-space: pre;
}
js
//PREVIEW
function showPreview() {
var htmlCode = document.getElementById("htmlCode").innerText;
var cssCode =
"<style>" + document.getElementById("cssCode").value + "</style>";
var jsCode =
"<scri" + "pt>" + document.getElementById("jsCode").value + "</scri" + "pt>";
var frame = document.getElementById("preview-window").contentWindow.document;
document.getElementById("preview-window").srcdoc = htmlCode;
frame.open();
frame.write(htmlCode + cssCode + jsCode);
frame.write(editor);
frame.close();
}
showPreview()
2
Answers
you can apply React to your project with CDN.
Here is the URL: https://legacy.reactjs.org/docs/cdn-links.html
We need to use a compiler like babel to render the jsx and tsx components into js.
In this case, we can use babel standalone.
I created a variable with code equivalent to a html page with the react code from the editor and loaded it to the iframe.
I needed to do couple of things to make this work
<script data-plugins='transform-modules-umd' type='text/babel'>
around the react codeTo run the code, Just copy the code, paste it in a text editor and save it as .html and open in any recent browser.
Code:
This can be used as a building block to build complex use cases.
Seems like i cannot preview the code here because some security warning(probably iframe), So attaching a screenshot.