### Install Monaco Editor for React Source: https://github.com/suren-atoyan/monaco-react/blob/master/README.md Commands to install the library via npm or yarn. Ensure the monaco-editor package is installed as a peer dependency for TypeScript support. ```bash npm install @monaco-editor/react ``` ```bash yarn add @monaco-editor/react ``` -------------------------------- ### Using beforeMount for Pre-Editor Setup in Monaco React Source: https://github.com/suren-atoyan/monaco-react/blob/master/v4.changes.md The new `beforeMount` prop allows execution of code before the Monaco editor is initialized. It exposes the Monaco instance as the first argument, enabling setup tasks or configurations prior to mounting. ```javascript function beforeMount(monaco: Monaco) => { console.log('Monaco instance available before mount:', monaco); // Perform setup tasks here } ``` -------------------------------- ### Multi-Model Editor Example in Monaco React Source: https://github.com/suren-atoyan/monaco-react/blob/master/v4.changes.md Monaco React v4 introduces support for multi-model editors. This allows managing multiple files or code models within a single editor instance. The example demonstrates a basic setup for this feature. ```javascript // Refer to the provided CodeSandbox link for a detailed demo: // https://codesandbox.io/s/multi-model-editor-kugi6?file=/src/App.js ``` -------------------------------- ### DiffEditor Component Usage Source: https://context7.com/suren-atoyan/monaco-react/llms.txt Demonstrates how to integrate and use the DiffEditor component for comparing code versions. It includes example code for setting up the editor, providing original and modified code, and handling editor mounting and value retrieval. ```APIDOC ## DiffEditor Component ### Description The DiffEditor component renders a side-by-side comparison of two code versions, highlighting additions, deletions, and modifications. It supports separate languages and model paths for each side, making it ideal for code review interfaces, version comparison tools, and merge conflict resolution. ### Usage Example ```jsx import React, { useRef } from 'react'; import { DiffEditor } from '@monaco-editor/react'; function CodeDiffViewer() { const diffEditorRef = useRef(null); const originalCode = `function calculateTotal(items) { let total = 0; for (let i = 0; i < items.length; i++) { total += items[i].price; } return total; }`; const modifiedCode = `function calculateTotal(items) { return items.reduce((total, item) => { return total + item.price * (1 - (item.discount || 0)); }, 0); }`; function handleDiffEditorMount(editor, monaco) { diffEditorRef.current = editor; } function getOriginalValue() { if (diffEditorRef.current) { const value = diffEditorRef.current.getOriginalEditor().getValue(); console.log('Original:', value); return value; } } function getModifiedValue() { if (diffEditorRef.current) { const value = diffEditorRef.current.getModifiedEditor().getValue(); console.log('Modified:', value); return value; } } return (
Loading diff editor...
} /> ); } export default CodeDiffViewer; ``` ### Props - **height** (string) - Required - The height of the editor. - **language** (string) - Optional - The language mode for the editor (e.g., 'javascript', 'python'). - **original** (string) - Required - The initial content for the original code side. - **modified** (string) - Required - The initial content for the modified code side. - **theme** (string) - Optional - The editor theme (e.g., 'vs-dark', 'light'). - **options** (object) - Optional - Configuration options for the DiffEditor. - **readOnly** (boolean) - Optional - If true, the editor is read-only. - **renderSideBySide** (boolean) - Optional - If true, renders the diff side-by-side. - **originalEditable** (boolean) - Optional - If true, the original side is editable. - **onMount** (function) - Optional - Callback function when the editor is mounted. Receives the editor instance and Monaco editor API. - **loading** (ReactNode) - Optional - Content to display while the editor is loading. ``` -------------------------------- ### Monaco Editor with Extended Event Handling in React Source: https://github.com/suren-atoyan/monaco-react/blob/master/README.md This example extends the basic integration by demonstrating how to utilize various event handlers provided by the Monaco Editor component. It includes handlers for editor changes, mounting, before mounting, and validation, allowing for more dynamic editor interactions. ```javascript import React from 'react'; import ReactDOM from 'react-dom'; import Editor from '@monaco-editor/react'; function App() { function handleEditorChange(value, event) { // here is the current value } function handleEditorDidMount(editor, monaco) { console.log('onMount: the editor instance:', editor); console.log('onMount: the monaco instance:', monaco); } function handleEditorWillMount(monaco) { console.log('beforeMount: the monaco instance:', monaco); } function handleEditorValidation(markers) { // model markers // markers.forEach(marker => console.log('onValidate:', marker.message)); } return ( ); } const rootElement = document.getElementById('root'); ReactDOM.render(, rootElement); ``` -------------------------------- ### Get Monaco Editor Instance in React Source: https://github.com/suren-atoyan/monaco-react/blob/master/README.md Demonstrates how to access the Monaco Editor instance using the 'onMount' prop. The instance is passed as the first argument to the callback, allowing you to store it in a ref for later use. ```javascript import React, { useRef } from 'react'; import ReactDOM from 'react-dom'; import Editor from '@monaco-editor/react'; function App() { const editorRef = useRef(null); function handleEditorDidMount(editor, monaco) { // here is the editor instance // you can store it in `useRef` for further usage editorRef.current = editor; } return ( ); } const rootElement = document.getElementById('root'); ReactDOM.render(, rootElement); ``` -------------------------------- ### Get Monaco Instance in React Source: https://github.com/suren-atoyan/monaco-react/blob/master/README.md Shows multiple ways to obtain the Monaco instance. It can be accessed via the 'onMount' or 'beforeMount' props, using the 'loader' utility, or through the 'useMonaco' hook. The 'beforeMount' prop allows configuration before the editor is fully mounted. ```javascript import React, { useRef } from 'react'; import ReactDOM from 'react-dom'; import Editor from '@monaco-editor/react'; function App() { const monacoRef = useRef(null); function handleEditorWillMount(monaco) { // here is the monaco instance // do something before editor is mounted monaco.languages.typescript.javascriptDefaults.setEagerModelSync(true); } function handleEditorDidMount(editor, monaco) { // here is another way to get monaco instance // you can also store it in `useRef` for further usage monacoRef.current = monaco; } return ( ); } const rootElement = document.getElementById('root'); ReactDOM.render(, rootElement); ``` ```javascript import { loader } from '@monaco-editor/react'; loader.init().then((monaco) => console.log('here is the monaco instance:', monaco)); ``` ```javascript import React, { useEffect } from 'react'; import ReactDOM from 'react-dom'; import Editor, { useMonaco } from '@monaco-editor/react'; function App() { const monaco = useMonaco(); useEffect(() => { if (monaco) { console.log('here is the monaco instance:', monaco); } }, [monaco]); return ; } const rootElement = document.getElementById('root'); ReactDOM.render(, rootElement); ``` -------------------------------- ### Simple Monaco Editor Integration in React Source: https://github.com/suren-atoyan/monaco-react/blob/master/README.md This snippet shows the basic setup for embedding the Monaco Editor within a React application. It requires importing the Editor component and rendering it with basic configuration like height and default language. ```javascript import React from 'react'; import ReactDOM from 'react-dom'; import Editor from '@monaco-editor/react'; function App() { return ; } const rootElement = document.getElementById('root'); ReactDOM.render(, rootElement); ``` -------------------------------- ### Getting Monaco Editor Value via onChange Prop in React Source: https://github.com/suren-atoyan/monaco-react/blob/master/README.md This example demonstrates an alternative method for obtaining the Monaco Editor's content: by using the `onChange` prop. The callback function passed to `onChange` receives the current editor value as an argument, allowing for real-time updates or processing as the user types. ```javascript import React from 'react'; import ReactDOM from 'react-dom'; import Editor from '@monaco-editor/react'; function App() { function handleEditorChange(value, event) { console.log('here is the current model value:', value); } return ( ); } const rootElement = document.getElementById('root'); ReactDOM.render(, rootElement); ``` -------------------------------- ### Getting DiffEditor Values via Editor Instance in React Source: https://github.com/suren-atoyan/monaco-react/blob/master/README.md This snippet shows how to retrieve values from a `DiffEditor` component using a ref. It specifically demonstrates accessing the original and modified editor instances via `diffEditorRef.current.getOriginalEditor()` and `diffEditorRef.current.getModifiedEditor()` respectively, allowing you to get the content of each side of the diff. ```javascript import React, { useRef } from 'react'; import ReactDOM from 'react-dom'; import { DiffEditor } from '@monaco-editor/react'; function App() { const diffEditorRef = useRef(null); function handleEditorDidMount(editor, monaco) { diffEditorRef.current = editor; } function showOriginalValue() { alert(diffEditorRef.current.getOriginalEditor().getValue()); } function showModifiedValue() { alert(diffEditorRef.current.getModifiedEditor().getValue()); } return ( <> ); } const rootElement = document.getElementById('root'); ReactDOM.render(, rootElement); ``` -------------------------------- ### Getting Monaco Editor Value via Editor Instance in React Source: https://github.com/suren-atoyan/monaco-react/blob/master/README.md This snippet illustrates how to retrieve the current content of the Monaco Editor using a ref to the editor instance. The `onMount` handler captures the editor instance, and a separate function uses `editorRef.current.getValue()` to access the editor's content, typically triggered by a button click. ```javascript import React, { useRef } from 'react'; import ReactDOM from 'react-dom'; import Editor from '@monaco-editor/react'; function App() { const editorRef = useRef(null); function handleEditorDidMount(editor, monaco) { editorRef.current = editor; } function showValue() { alert(editorRef.current.getValue()); } return ( <> ); } const rootElement = document.getElementById('root'); ReactDOM.render(, rootElement); ``` -------------------------------- ### Import Monaco Editor Components Source: https://github.com/suren-atoyan/monaco-react/blob/master/README.md How to import the main Editor, DiffEditor components, the useMonaco hook, and the loader utility from the package. ```javascript import Editor, { DiffEditor, useMonaco, loader } from '@monaco-editor/react'; ``` -------------------------------- ### Import Monaco Editor as npm Package (General) Source: https://github.com/suren-atoyan/monaco-react/blob/master/README.md Demonstrates the basic import of the Monaco Editor from node_modules and its configuration using the loader. This method is suitable for general npm package usage. ```javascript import * as monaco from 'monaco-editor'; import { loader } from '@monaco-editor/react'; loader.config({ monaco }); // ... ``` -------------------------------- ### Basic Monaco Editor Integration in React Source: https://context7.com/suren-atoyan/monaco-react/llms.txt Demonstrates how to render a basic Monaco code editor instance within a React component. It covers essential props like height, width, language, default value, theme, and options. It also shows how to access the editor and Monaco instances using the `onMount` callback for advanced configurations and event handling. ```jsx import React, { useRef } from 'react'; import Editor from '@monaco-editor/react'; function CodeEditor() { const editorRef = useRef(null); function handleEditorDidMount(editor, monaco) { // Store editor reference for later use editorRef.current = editor; // Configure TypeScript defaults monaco.languages.typescript.javascriptDefaults.setEagerModelSync(true); // Add custom keyboard shortcut editor.addCommand(monaco.KeyMod.CtrlCmd | monaco.KeyCode.KeyS, () => { console.log('Save triggered, value:', editor.getValue()); }); } function handleEditorChange(value, event) { console.log('Content changed:', value); } function handleEditorValidation(markers) { // Handle validation markers (errors, warnings) markers.forEach(marker => { console.log(`${marker.severity === 8 ? 'Error' : 'Warning'}: ${marker.message} at line ${marker.startLineNumber}`); }); } return ( Loading editor...} /> ); } export default CodeEditor; ``` -------------------------------- ### Configure Monaco Loader Options Source: https://context7.com/suren-atoyan/monaco-react/llms.txt Configure Monaco Editor's loading mechanism, including CDN paths, locale settings, and integration with npm packages. This allows for offline usage or custom bundling. The loader.init() method provides access to the Monaco instance for further configuration, such as setting TypeScript compiler options and adding extra type definitions. ```jsx import { loader } from '@monaco-editor/react'; import Editor from '@monaco-editor/react'; // Option 1: Configure CDN paths loader.config({ paths: { vs: 'https://cdn.jsdelivr.net/npm/monaco-editor@0.45.0/min/vs', }, }); // Option 2: Configure locale loader.config({ 'vs/nls': { availableLanguages: { '*': 'de', // German locale }, }, }); // Option 3: Use monaco-editor as npm package // import * as monaco from 'monaco-editor'; // loader.config({ monaco }); // Option 4: Access Monaco instance directly loader.init().then((monaco) => { console.log('Monaco loaded:', monaco.editor.EditorType); // Pre-configure Monaco before any editor mounts monaco.languages.typescript.typescriptDefaults.setCompilerOptions({ target: monaco.languages.typescript.ScriptTarget.ES2020, allowNonTsExtensions: true, moduleResolution: monaco.languages.typescript.ModuleResolutionKind.NodeJs, module: monaco.languages.typescript.ModuleKind.CommonJS, noEmit: true, typeRoots: ['node_modules/@types'], }); // Add extra type definitions monaco.languages.typescript.typescriptDefaults.addExtraLib( `declare module 'mylib' { export function doSomething(): void; }`, 'ts:mylib.d.ts' ); }); function ConfiguredEditor() { return ( ); } export default ConfiguredEditor; ``` -------------------------------- ### Configure Monaco Theme and Language Provider with useMonaco (React) Source: https://context7.com/suren-atoyan/monaco-react/llms.txt This snippet demonstrates how to use the `useMonaco` hook to define a custom theme and register a language completion provider for JavaScript. It ensures that Monaco is loaded before attempting to configure it, providing a custom editor experience with tailored suggestions and styling. ```jsx import React, { useEffect, useState } from 'react'; import Editor, { useMonaco } from '@monaco-editor/react'; function EditorWithCustomTheme() { const monaco = useMonaco(); const [isThemeReady, setIsThemeReady] = useState(false); useEffect(() => { if (monaco) { // Define a custom theme monaco.editor.defineTheme('myCustomTheme', { base: 'vs-dark', inherit: true, rules: [ { token: 'comment', foreground: '6A9955', fontStyle: 'italic' }, { token: 'keyword', foreground: 'C586C0' }, { token: 'string', foreground: 'CE9178' }, { token: 'number', foreground: 'B5CEA8' }, { token: 'function', foreground: 'DCDCAA' }, ], colors: { 'editor.background': '#1a1a2e', 'editor.foreground': '#eaeaea', 'editorLineNumber.foreground': '#5a5a7a', 'editor.selectionBackground': '#3a3a5a', 'editor.lineHighlightBackground': '#2a2a4a', }, }); // Register custom completion provider for JavaScript monaco.languages.registerCompletionItemProvider('javascript', { provideCompletionItems: (model, position) => { const word = model.getWordUntilPosition(position); const range = { startLineNumber: position.lineNumber, endLineNumber: position.lineNumber, startColumn: word.startColumn, endColumn: word.endColumn, }; return { suggestions: [ { label: 'console.log', kind: monaco.languages.CompletionItemKind.Snippet, insertText: 'console.log(${1:message});', insertTextRules: monaco.languages.CompletionItemInsertTextRule.InsertAsSnippet, documentation: 'Log output to console', range, }, { label: 'async function', kind: monaco.languages.CompletionItemKind.Snippet, insertText: 'async function ${1:name}(${2:params}) {\n\t${3:// body}\n}', insertTextRules: monaco.languages.CompletionItemInsertTextRule.InsertAsSnippet, documentation: 'Async function declaration', range, }, ], }; }, }); setIsThemeReady(true); } }, [monaco]); if (!isThemeReady) { return
Loading Monaco...
; } return ( ); } export default EditorWithCustomTheme; ``` -------------------------------- ### Loader Configuration API Source: https://context7.com/suren-atoyan/monaco-react/llms.txt Configures the Monaco Editor source location, locale settings, and provides methods for instance initialization. ```APIDOC ## POST /loader/config ### Description Configures the environment for the Monaco Editor, including CDN paths, internationalization locales, or local npm package references. ### Method POST ### Endpoint loader.config(options) ### Parameters #### Request Body - **paths** (object) - Optional - Defines the 'vs' path for CDN or local file loading. - **vs/nls** (object) - Optional - Configuration for internationalization (availableLanguages). - **monaco** (object) - Optional - Pass an existing monaco-editor instance for bundling. ### Request Example { "paths": { "vs": "https://cdn.jsdelivr.net/npm/monaco-editor@0.45.0/min/vs" } } ### Response #### Success Response (200) - **status** (string) - Configuration applied successfully. ``` -------------------------------- ### Configure Vite for Local Monaco Bundling Source: https://context7.com/suren-atoyan/monaco-react/llms.txt Shows how to configure Vite to bundle Monaco locally, bypassing CDN dependencies. This requires setting up custom workers and initializing the loader before the Editor component is used. ```javascript // vite.config.js import { defineConfig } from 'vite'; import react from '@vitejs/plugin-react'; export default defineConfig({ plugins: [react()], optimizeDeps: { include: ['monaco-editor'], }, }); // src/monacoConfig.js import { loader } from '@monaco-editor/react'; import * as monaco from 'monaco-editor'; import editorWorker from 'monaco-editor/esm/vs/editor/editor.worker?worker'; import jsonWorker from 'monaco-editor/esm/vs/language/json/json.worker?worker'; import cssWorker from 'monaco-editor/esm/vs/language/css/css.worker?worker'; import htmlWorker from 'monaco-editor/esm/vs/language/html/html.worker?worker'; import tsWorker from 'monaco-editor/esm/vs/language/typescript/ts.worker?worker'; self.MonacoEnvironment = { getWorker(_, label) { if (label === 'json') return new jsonWorker(); if (label === 'css' || label === 'scss' || label === 'less') return new cssWorker(); if (label === 'html' || label === 'handlebars' || label === 'razor') return new htmlWorker(); if (label === 'typescript' || label === 'javascript') return new tsWorker(); return new editorWorker(); }, }; loader.config({ monaco }); export { monaco }; // src/App.jsx import './monacoConfig'; import Editor from '@monaco-editor/react'; function App() { return ( ); } export default App; ``` -------------------------------- ### Configure ESLint with React Plugin and Recommended Rules Source: https://github.com/suren-atoyan/monaco-react/blob/master/demo/README.md This snippet demonstrates how to configure ESLint to use the `eslint-plugin-react`. It sets the React version, adds the plugin, and enables its recommended rules, including those for `jsx-runtime`. ```javascript // eslint.config.js import react from 'eslint-plugin-react' export default tseslint.config({ // Set the react version settings: { react: { version: '18.3' } }, plugins: { // Add the react plugin react, }, rules: { // other rules... // Enable its recommended rules ...react.configs.recommended.rules, ...react.configs['jsx-runtime'].rules, }, }) ``` -------------------------------- ### Monaco Editor Lifecycle Events (JavaScript) Source: https://github.com/suren-atoyan/monaco-react/blob/master/README.md Defines event handlers for the Monaco editor's lifecycle. `beforeMount` is called before the editor is initialized, receiving the Monaco instance. `onMount` is called after the editor is initialized, receiving both the editor instance and the Monaco instance. ```javascript beforeMount: function(monaco) { // Custom logic before editor mounts }, onMount: function(editor, monaco) { // Custom logic after editor mounts } ``` -------------------------------- ### Configuring Monaco Editor Lifecycle and Event Callbacks Source: https://github.com/suren-atoyan/monaco-react/blob/master/README.md This snippet demonstrates how to implement the core event handlers for the Monaco editor component. It includes hooks for initialization, content changes, and validation markers. ```javascript console.log('Before mount:', monaco)} onMount={(editor, monaco) => console.log('Editor mounted:', editor)} onChange={(value, ev) => console.log('Content changed:', value)} onValidate={(markers) => console.log('Validation markers:', markers)} /> ``` -------------------------------- ### Create Custom Monaco Editor Instance Source: https://github.com/suren-atoyan/monaco-react/blob/master/README.md This snippet demonstrates how to create a custom Monaco editor instance using the '@monaco-editor/loader'. It initializes the loader, obtains the Monaco instance, and then creates an editor within a specified DOM element with custom properties and dimensions. ```javascript import loader from '@monaco-editor/loader'; loader.init().then((monaco) => { const wrapper = document.getElementById('root'); wrapper.style.height = '100vh'; const properties = { value: 'function hello() { alert("Hello world!"); }', language: 'javascript', }; monaco.editor.create(wrapper, properties); }); ``` -------------------------------- ### Implement Multi-model Editor in React Source: https://github.com/suren-atoyan/monaco-react/blob/master/README.md Demonstrates how to create a multi-model editor in Monaco React. It uses the 'path' prop to manage different editor models, allowing users to switch between files while preserving view state, text selection, and undo history. This enables IDE-like tab functionality. ```javascript const files = { 'script.js': { name: 'script.js', language: 'javascript', value: someJSCodeExample, }, 'style.css': { name: 'style.css', language: 'css', value: someCSSCodeExample, }, 'index.html': { name: 'index.html', language: 'html', value: someHTMLCodeExample, }, }; import React, { useState } from 'react'; import ReactDOM from 'react-dom'; import Editor from '@monaco-editor/react'; function App() { const [fileName, setFileName] = useState('script.js'); const file = files[fileName]; return ( <> ); } const rootElement = document.getElementById('root'); ReactDOM.render(, rootElement); ``` -------------------------------- ### Configure Monaco Editor Workers with Vite Source: https://github.com/suren-atoyan/monaco-react/blob/master/README.md Provides a detailed configuration for setting up Monaco Editor workers when using Vite as the build tool. This includes importing specific worker modules for different languages and configuring the MonacoEnvironment. ```javascript import { loader } from '@monaco-editor/react'; import * as monaco from 'monaco-editor'; import editorWorker from 'monaco-editor/esm/vs/editor/editor.worker?worker'; import jsonWorker from 'monaco-editor/esm/vs/language/json/json.worker?worker'; import cssWorker from 'monaco-editor/esm/vs/language/css/css.worker?worker'; import htmlWorker from 'monaco-editor/esm/vs/language/html/html.worker?worker'; import tsWorker from 'monaco-editor/esm/vs/language/typescript/ts.worker?worker'; self.MonacoEnvironment = { getWorker(_, label) { if (label === 'json') { return new jsonWorker(); } if (label === 'css' || label === 'scss' || label === 'less') { return new cssWorker(); } if (label === 'html' || label === 'handlebars' || label === 'razor') { return new htmlWorker(); } if (label === 'typescript' || label === 'javascript') { return new tsWorker(); } return new editorWorker(); }, }; loader.config({ monaco }); loader.init().then(/* ... */); ``` -------------------------------- ### Multi-model Editor Configuration Source: https://github.com/suren-atoyan/monaco-react/blob/master/README.md Configuring the Editor component to support multiple files or tabs by utilizing the 'path' property as a unique model identifier. ```APIDOC ## Component Property: path ### Description The 'path' property acts as an identifier for the editor model. When provided, the Editor component checks for an existing model associated with that path. If found, it restores the model (including view state, scroll position, and undo stack); otherwise, it creates a new one. ### Parameters - **path** (string) - Required - Unique identifier for the model (e.g., file path). - **value** (string) - Optional - The content of the editor. - **language** (string) - Optional - The language mode of the editor. - **saveViewState** (boolean) - Optional - Whether to persist view state between model switches. ### Usage Example ``` -------------------------------- ### useMonaco Hook Source: https://context7.com/suren-atoyan/monaco-react/llms.txt The useMonaco hook returns the Monaco instance asynchronously, allowing for advanced editor configuration. ```APIDOC ## useMonaco Hook ### Description The `useMonaco` hook provides access to the Monaco namespace object. It is useful for configuring themes, registering language providers, or adding custom completion items independently of the Editor component instance. ### Method N/A (React Hook) ### Parameters - **None** ### Returns - **monaco** (Object|null) - The Monaco instance object. Returns `null` until the Monaco library has finished loading. ### Usage Example ```jsx import { useMonaco } from '@monaco-editor/react'; const MyComponent = () => { const monaco = useMonaco(); useEffect(() => { if (monaco) { // Access monaco.editor, monaco.languages, etc. monaco.editor.defineTheme('myTheme', { ... }); } }, [monaco]); return
Editor logic here
; }; ``` ``` -------------------------------- ### Integrate Monaco Editor with Next.js App Router Source: https://context7.com/suren-atoyan/monaco-react/llms.txt Demonstrates how to use the Monaco Editor in a Next.js environment. It uses dynamic imports with SSR disabled to ensure compatibility with browser-only Monaco APIs. ```jsx 'use client'; import dynamic from 'next/dynamic'; import { useState } from 'react'; const Editor = dynamic(() => import('@monaco-editor/react'), { ssr: false, loading: () =>
Loading editor...
, }); export default function EditorPage() { const [output, setOutput] = useState(''); const handleEditorChange = (value) => { try { if (value && value.trim().startsWith('//')) { setOutput('Add code below the comment to see output'); } } catch (e) { setOutput(`Error: ${e.message}`); } }; return (

Code Editor

{output && (
          {output}
        
)}
); } ``` -------------------------------- ### Implement React DiffEditor for Code Comparison Source: https://context7.com/suren-atoyan/monaco-react/llms.txt This snippet demonstrates how to use the DiffEditor component from '@monaco-editor/react' to display a side-by-side comparison of two code versions. It includes functionality to mount the editor, retrieve values from both the original and modified sides, and basic UI elements for interaction. The component supports customization of height, language, theme, and editor options. ```jsx import React, { useRef } from 'react'; import { DiffEditor } from '@monaco-editor/react'; function CodeDiffViewer() { const diffEditorRef = useRef(null); const originalCode = `function calculateTotal(items) { let total = 0; for (let i = 0; i < items.length; i++) { total += items[i].price; } return total; }`; const modifiedCode = `function calculateTotal(items) { return items.reduce((total, item) => { return total + item.price * (1 - (item.discount || 0)); }, 0); }`; function handleDiffEditorMount(editor, monaco) { diffEditorRef.current = editor; } function getOriginalValue() { if (diffEditorRef.current) { const value = diffEditorRef.current.getOriginalEditor().getValue(); console.log('Original:', value); return value; } } function getModifiedValue() { if (diffEditorRef.current) { const value = diffEditorRef.current.getModifiedEditor().getValue(); console.log('Modified:', value); return value; } } return (
Loading diff editor...
} /> ); } export default CodeDiffViewer; ``` -------------------------------- ### Configuring Monaco Editor Loader in Monaco React Source: https://github.com/suren-atoyan/monaco-react/blob/master/v4.changes.md The `monaco` utility has been renamed to `loader`. This provides configuration options for loading the Monaco editor, such as setting CDN paths or customizing loader behavior. ```javascript import { loader } from '@monaco-editor/react'; loader.config({ paths: { vs: 'https://unpkg.com/monaco-editor@0.33.0/min/vs' } }); // Then use the Editor component as usual ``` -------------------------------- ### Configure Monaco Editor Loader Source: https://github.com/suren-atoyan/monaco-react/blob/master/README.md The 'loader' utility from '@monaco-editor/react' allows customization of the Monaco AMD loader. You can change the CDN source for Monaco files or configure localization settings by providing a configuration object to 'loader.config()'. ```javascript import { loader } from '@monaco-editor/react'; // you can change the source of the monaco files loader.config({ paths: { vs: '...' } }); // you can configure the locales loader.config({ 'vs/nls': { availableLanguages: { '*': 'de' } } }); // or loader.config({ paths: { vs: '...', }, 'vs/nls': { availableLanguages: { '*': 'de', }, }, }); ``` -------------------------------- ### Using the useMonaco Hook Source: https://github.com/suren-atoyan/monaco-react/blob/master/README.md The 'useMonaco' hook provides a convenient way to access the Monaco instance in functional React components. It's important to note that monaco initialization is asynchronous. The hook might initially return null, so conditional checks are necessary before using the instance. ```javascript import React, { useEffect } from 'react'; import ReactDOM from 'react-dom'; import Editor, { useMonaco } from '@monaco-editor/react'; function App() { const monaco = useMonaco(); useEffect(() => { // do conditional chaining monaco?.languages.typescript.javascriptDefaults.setEagerModelSync(true); // or make sure that it exists by other ways if (monaco) { console.log('here is the monaco instance:', monaco); } }, [monaco]); return ; } const rootElement = document.getElementById('root'); ReactDOM.render(, rootElement); ``` -------------------------------- ### Setting Default Path and Language in Monaco React Source: https://github.com/suren-atoyan/monaco-react/blob/master/v4.changes.md New props `defaultPath` and `defaultLanguage` allow specifying the initial path and language for the editor's default model. These are used when creating the model via `monaco.editor.createModel`. ```javascript ``` -------------------------------- ### Multi-Model Monaco Editor for Tabbed Editing in React Source: https://context7.com/suren-atoyan/monaco-react/llms.txt Implements an IDE-like tabbed editing experience using the Monaco Editor component. Each tab represents a different file with its own language, content, and undo history. The `path` prop is crucial for managing multiple models, and `saveViewState` preserves user interaction states like cursor position and scroll. ```jsx import React, { useState } from 'react'; import Editor from '@monaco-editor/react'; const files = { 'index.js': { name: 'index.js', language: 'javascript', value: `import React from 'react'; import { render } from 'react-dom'; import App from './App'; render(, document.getElementById('root'));`, }, 'App.jsx': { name: 'App.jsx', language: 'javascript', value: `import React from 'react'; export default function App() { return
Hello World!
; }`, }, 'styles.css': { name: 'styles.css', language: 'css', value: `body { margin: 0; font-family: sans-serif; } .container { padding: 20px; }`, }, }; function MultiFileEditor() { const [currentFile, setCurrentFile] = useState('index.js'); const file = files[currentFile]; return (
{Object.keys(files).map((fileName) => ( ))}
); } export default MultiFileEditor; ``` -------------------------------- ### Configure ESLint Parser Options for Type-Aware Linting Source: https://github.com/suren-atoyan/monaco-react/blob/master/demo/README.md This snippet shows how to configure the top-level `parserOptions` in ESLint to enable type-aware lint rules. It specifies the TypeScript project files and the root directory for parsing. ```javascript export default tseslint.config({ languageOptions: { // other options... parserOptions: { project: ['./tsconfig.node.json', './tsconfig.app.json'], tsconfigRootDir: import.meta.dirname, }, }, }) ``` -------------------------------- ### Configure Monaco Editor Local Path in Electron Source: https://github.com/suren-atoyan/monaco-react/blob/master/README.md This snippet shows how to configure the Monaco Editor loader to use local paths instead of CDN, which is often necessary in Electron environments. It modifies the loader's configuration to point to a local 'vs' directory. ```javascript import { loader } from '@monaco-editor/react'; loader.config({ paths: { vs: '../path-to-monaco' } }); ``` -------------------------------- ### Component: Editor Source: https://github.com/suren-atoyan/monaco-react/blob/master/README.md The primary component for rendering the Monaco Editor in a React application. ```APIDOC ## ### Description The Editor component renders the Monaco Editor instance. It handles the loading of the editor and provides callbacks for lifecycle events. ### Method N/A (React Component) ### Parameters #### Props - **height** (string/number) - Optional - Height of the editor container. - **width** (string/number) - Optional - Width of the editor container. - **language** (string) - Optional - The programming language for syntax highlighting. - **value** (string) - Optional - The initial content of the editor. - **defaultValue** (string) - Optional - The default content of the editor. - **theme** (string) - Optional - The theme of the editor (e.g., 'light', 'vs-dark'). - **onMount** (function) - Optional - Callback triggered when the editor instance is ready. - **onChange** (function) - Optional - Callback triggered when the editor content changes. ### Request Example ### Response #### Success Response - **editor** (object) - The monaco editor instance. - **monaco** (object) - The monaco global instance. ``` -------------------------------- ### Hook: useMonaco Source: https://github.com/suren-atoyan/monaco-react/blob/master/README.md A React hook that provides access to the monaco instance, allowing for direct interaction with the editor's API. ```APIDOC ## useMonaco() ### Description This hook returns the monaco instance once it has been loaded. It is useful for performing operations that require the global monaco object. ### Method N/A (React Hook) ### Parameters None ### Request Example const monaco = useMonaco(); ### Response #### Success Response - **monaco** (object) - The monaco global instance or null if not yet loaded. ``` -------------------------------- ### Configure Monaco Editor Absolute URL Path in Electron Source: https://github.com/suren-atoyan/monaco-react/blob/master/README.md This code configures the Monaco Editor loader to use an absolute URL path, essential for Electron applications when loading from 'node_modules'. It includes utility functions to ensure correct path resolution and encoding for file URIs. ```javascript import path from 'path'; import { loader } from '@monaco-editor/react'; function ensureFirstBackSlash(str) { return str.length > 0 && str.charAt(0) !== '/' ? '/' + str : str; } function uriFromPath(_path) { const pathName = path.resolve(_path).replace(/\/g, '/'); return encodeURI('file://' + ensureFirstBackSlash(pathName)); } loader.config({ paths: { vs: uriFromPath(path.join(__dirname, '../node_modules/monaco-editor/min/vs')), }, }); ``` -------------------------------- ### Replacing editorDidMount with onMount in Monaco React Source: https://github.com/suren-atoyan/monaco-react/blob/master/v4.changes.md The `editorDidMount` prop has been removed in v4 and replaced by `onMount`. The `onMount` prop provides the Monaco editor instance and the Monaco object, allowing direct access to editor functionalities like `editor.getValue()`. ```javascript function onMount(editor: monaco.editor.IStandaloneCodeEditor, monaco: Monaco) => void { // Use editor.getValue() to get the current value const currentValue = editor.getValue(); console.log('Editor mounted:', editor, monaco); } ``` -------------------------------- ### Editor Component Props Source: https://github.com/suren-atoyan/monaco-react/blob/master/README.md This section details the available props for the Monaco Editor React component, allowing for customization of its behavior and appearance. ```APIDOC ## Editor Component Props This section details the available props for the Monaco Editor React component, allowing for customization of its behavior and appearance. ### Props #### `defaultValue` (string) - Description: Default value of the current model. #### `defaultLanguage` (string) - Description: Default language of the current model. #### `defaultPath` (string) - Description: Default path of the current model. Will be passed as the third argument to `.createModel` method - `monaco.editor.createModel(..., ..., monaco.Uri.parse(defaultPath))`. #### `value` (string) - Description: Value of the current model. #### `language` (enum: ...) - Description: Language of the current model (all languages that are [supported](https://github.com/microsoft/monaco-editor/tree/main/src/basic_languages) by monaco-editor). #### `path` (string) - Description: Path of the current model. Will be passed as the third argument to `.createModel` method - `monaco.editor.createModel(..., ..., monaco.Uri.parse(defaultPath))`. #### `theme` (enum: "light" | "vs-dark") - Default: "light" - Description: The theme for the monaco. Available options "vs-dark" | "light". Define new themes by `monaco.editor.defineTheme`. #### `line` (number) - Description: The line to jump on it. #### `loading` (React Node) - Default: "Loading..." - Description: The loading screen before the editor will be mounted. #### `options` (object) - Default: {} - Description: [IStandaloneEditorConstructionOptions](https://microsoft.github.io/monaco-editor/docs.html#interfaces/editor_editor_api.editor.IStandaloneEditorConstructionOptions.html). #### `overrideServices` (object) - Default: {} - Description: [IEditorOverrideServices](https://microsoft.github.io/monaco-editor/typedoc/interfaces/editor_editor_api.editor.IEditorOverrideServices.html). #### `saveViewState` (boolean) - Default: true - Description: Indicator whether to save the models' view states between model changes or not. #### `keepCurrentModel` (boolean) - Default: false - Description: Indicator whether to dispose the current model when the Editor is unmounted or not. #### `width` (union: number | string) - Default: "100%" - Description: Width of the editor wrapper. ``` -------------------------------- ### Using the useMonaco Hook in Monaco React Source: https://github.com/suren-atoyan/monaco-react/blob/master/v4.changes.md The `useMonaco` hook provides a convenient way to access the Monaco editor instance within your React components. It returns the Monaco object, allowing you to interact with the editor's API. ```javascript import { useMonaco } from '@monaco-editor/react'; function MyComponent() { const monaco = useMonaco(); React.useEffect(() => { if (monaco) { console.log('Monaco instance from hook:', monaco); } }, [monaco]); // ... rest of the component } ```