Welcome folks today in this blog post we will be building a visual studio
code editor in browser using the monaco
syntax highlighter library in react.js. All the full source code of the application is shown below.
Get Started
In order to get started you need to make a new react.js
project and install the monaco
library as shown below
npm create vite monacoproject
`
cd monacoproject
npm i @monaco-editor/react
And after thar you need to copy paste the following code inside the App.jsx
file and copy paste the following code
App.jsx
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 |
import React, { useRef, useState } from 'react' import Editor from '@monaco-editor/react' const files = { "script.js":{ name:"script.js", language:'javascript', value:"let name = 5" }, "script.py":{ name:"script.py", language:'python', value:"print('hello world')" }, "index.html":{ name:"index.html", language:'html', value:"<p>this is a paragraph</p>" } } function App() { const [fileName,setFileName] = useState("script.js") const editorRef = useRef(null) const file = files[fileName] function handleEditorDidMount(editor,monaco){ editorRef.current = editor } return ( <div> <button onClick={() => setFileName("index.html")}>Switch to index.html</button> <button onClick={() => setFileName("script.js")}>Switch to script.js</button> <button onClick={() => setFileName("script.py")}>Switch to script.py</button> <Editor height="100vh" width="100%" theme="vc-dark" onMount={handleEditorDidMount} path={file.name} defaultLanguage={file.language} defaultValue={file.value} /> </div> ) } export default App |