0
# Code Editor
1
2
The primary Monaco Editor React component providing full code editing capabilities with syntax highlighting, IntelliSense, autocomplete, and advanced editing features for any programming language.
3
4
## Capabilities
5
6
### Editor Component
7
8
Main editor component that wraps Monaco Editor with React-friendly props and event handling.
9
10
```typescript { .api }
11
/**
12
* Monaco Editor React component with full editing capabilities
13
* @param props - Editor configuration and event handlers
14
* @returns React component rendering Monaco Editor
15
*/
16
declare const Editor: React.ComponentType<EditorProps>;
17
18
interface EditorProps {
19
/** Default value of the current model */
20
defaultValue?: string;
21
/** Value of the current model (controlled) */
22
value?: string;
23
/** Default language of the current model */
24
defaultLanguage?: string;
25
/** Language of the current model */
26
language?: string;
27
/** Default path of the current model - passed to monaco.editor.createModel */
28
defaultPath?: string;
29
/** Path of the current model - passed to monaco.editor.createModel */
30
path?: string;
31
/** Theme for the monaco editor - 'vs-dark' | 'light' or custom theme name */
32
theme?: Theme | string;
33
/** Line number to jump to when editor mounts */
34
line?: number;
35
/** Loading component shown before editor is mounted */
36
loading?: ReactNode;
37
/** Monaco editor construction options */
38
options?: editor.IStandaloneEditorConstructionOptions;
39
/** Editor service overrides */
40
overrideServices?: editor.IEditorOverrideServices;
41
/** Whether to save view states between model changes */
42
saveViewState?: boolean;
43
/** Whether to keep current model when component unmounts */
44
keepCurrentModel?: boolean;
45
/** Width of editor wrapper */
46
width?: number | string;
47
/** Height of editor wrapper */
48
height?: number | string;
49
/** CSS class name for editor container */
50
className?: string;
51
/** Props applied to the wrapper element */
52
wrapperProps?: object;
53
/** Called before editor is mounted with monaco instance */
54
beforeMount?: BeforeMount;
55
/** Called when editor is mounted with editor and monaco instances */
56
onMount?: OnMount;
57
/** Called when editor content changes */
58
onChange?: OnChange;
59
/** Called when model validation completes */
60
onValidate?: OnValidate;
61
}
62
```
63
64
**Usage Examples:**
65
66
```typescript
67
import React, { useState } from "react";
68
import Editor from "@monaco-editor/react";
69
70
// Basic editor
71
function BasicEditor() {
72
return (
73
<Editor
74
height="400px"
75
defaultLanguage="javascript"
76
defaultValue="console.log('Hello Monaco!');"
77
/>
78
);
79
}
80
81
// Controlled editor with change handling
82
function ControlledEditor() {
83
const [code, setCode] = useState("const greeting = 'Hello World';");
84
85
const handleEditorChange = (value) => {
86
setCode(value || "");
87
};
88
89
return (
90
<Editor
91
height="400px"
92
language="javascript"
93
value={code}
94
onChange={handleEditorChange}
95
options={{
96
minimap: { enabled: false },
97
fontSize: 14,
98
}}
99
/>
100
);
101
}
102
103
// Multi-model editor
104
function MultiModelEditor() {
105
const [currentFile, setCurrentFile] = useState("file1.js");
106
107
const files = {
108
"file1.js": "console.log('File 1');",
109
"file2.ts": "const message: string = 'File 2';",
110
"file3.py": "print('File 3')"
111
};
112
113
return (
114
<div>
115
<select onChange={(e) => setCurrentFile(e.target.value)}>
116
{Object.keys(files).map(filename => (
117
<option key={filename} value={filename}>{filename}</option>
118
))}
119
</select>
120
<Editor
121
height="400px"
122
path={currentFile}
123
defaultLanguage={currentFile.split('.').pop()}
124
value={files[currentFile]}
125
options={{ readOnly: false }}
126
/>
127
</div>
128
);
129
}
130
```
131
132
### Event Handlers
133
134
Event handler functions for responding to editor lifecycle and content changes.
135
136
```typescript { .api }
137
/**
138
* Called when editor is mounted - provides access to editor and monaco instances
139
* @param editor - The standalone code editor instance
140
* @param monaco - The monaco editor namespace
141
*/
142
type OnMount = (editor: editor.IStandaloneCodeEditor, monaco: Monaco) => void;
143
144
/**
145
* Called before editor is mounted - allows monaco configuration
146
* @param monaco - The monaco editor namespace
147
*/
148
type BeforeMount = (monaco: Monaco) => void;
149
150
/**
151
* Called when editor content changes
152
* @param value - Current editor value (may be undefined)
153
* @param event - Monaco content change event with details
154
*/
155
type OnChange = (value: string | undefined, ev: editor.IModelContentChangedEvent) => void;
156
157
/**
158
* Called when model validation completes with error/warning markers
159
* @param markers - Array of validation markers (errors, warnings, info)
160
*/
161
type OnValidate = (markers: editor.IMarker[]) => void;
162
```
163
164
**Event Handler Examples:**
165
166
```typescript
167
import Editor from "@monaco-editor/react";
168
169
function EditorWithHandlers() {
170
const handleBeforeMount = (monaco) => {
171
// Configure monaco before editor creation
172
monaco.languages.typescript.javascriptDefaults.setEagerModelSync(true);
173
174
// Define custom theme
175
monaco.editor.defineTheme('myTheme', {
176
base: 'vs-dark',
177
inherit: true,
178
rules: [],
179
colors: {
180
'editor.background': '#1e1e1e',
181
}
182
});
183
};
184
185
const handleMount = (editor, monaco) => {
186
// Configure editor after mount
187
editor.focus();
188
editor.setPosition({ lineNumber: 1, column: 1 });
189
190
// Add custom commands
191
editor.addCommand(monaco.KeyMod.CtrlCmd | monaco.KeyCode.KeyS, () => {
192
console.log('Save command triggered');
193
});
194
};
195
196
const handleChange = (value, event) => {
197
console.log('Content changed:', value);
198
console.log('Change details:', event);
199
};
200
201
const handleValidate = (markers) => {
202
// Handle validation errors/warnings
203
const errors = markers.filter(m => m.severity === 8); // Error severity
204
const warnings = markers.filter(m => m.severity === 4); // Warning severity
205
206
console.log(`Validation: ${errors.length} errors, ${warnings.length} warnings`);
207
};
208
209
return (
210
<Editor
211
height="400px"
212
defaultLanguage="javascript"
213
beforeMount={handleBeforeMount}
214
onMount={handleMount}
215
onChange={handleChange}
216
onValidate={handleValidate}
217
theme="myTheme"
218
/>
219
);
220
}
221
```
222
223
### Editor Configuration Options
224
225
Configuration options for customizing editor behavior and appearance.
226
227
```typescript { .api }
228
// Core configuration props
229
interface EditorSizingProps {
230
/** Width of editor wrapper - default "100%" */
231
width?: number | string;
232
/** Height of editor wrapper - default "100%" */
233
height?: number | string;
234
/** CSS class name for editor container */
235
className?: string;
236
/** Props applied to wrapper element */
237
wrapperProps?: object;
238
}
239
240
interface EditorContentProps {
241
/** Initial editor content */
242
defaultValue?: string;
243
/** Controlled editor content */
244
value?: string;
245
/** Initial language mode */
246
defaultLanguage?: string;
247
/** Current language mode */
248
language?: string;
249
/** Initial model path/URI */
250
defaultPath?: string;
251
/** Current model path/URI */
252
path?: string;
253
}
254
255
interface EditorBehaviorProps {
256
/** Editor theme name */
257
theme?: Theme | string;
258
/** Line to jump to on mount */
259
line?: number;
260
/** Loading component during initialization */
261
loading?: ReactNode;
262
/** Save view state between model changes */
263
saveViewState?: boolean;
264
/** Keep model when unmounting */
265
keepCurrentModel?: boolean;
266
}
267
268
// Monaco editor native options (from monaco-editor package)
269
interface EditorMonacoOptions {
270
/** Monaco editor construction options */
271
options?: editor.IStandaloneEditorConstructionOptions;
272
/** Service overrides for advanced customization */
273
overrideServices?: editor.IEditorOverrideServices;
274
}
275
```
276
277
**Configuration Examples:**
278
279
```typescript
280
import Editor from "@monaco-editor/react";
281
282
// Customized editor appearance and behavior
283
function CustomizedEditor() {
284
const editorOptions = {
285
fontSize: 16,
286
lineHeight: 24,
287
minimap: { enabled: true },
288
scrollBeyondLastLine: false,
289
wordWrap: 'on',
290
automaticLayout: true,
291
tabSize: 2,
292
insertSpaces: true,
293
renderLineHighlight: 'all',
294
selectOnLineNumbers: true,
295
glyphMargin: true,
296
folding: true,
297
lineNumbers: 'on',
298
scrollbar: {
299
vertical: 'visible',
300
horizontal: 'visible',
301
},
302
};
303
304
return (
305
<Editor
306
height="500px"
307
width="100%"
308
language="typescript"
309
theme="vs-dark"
310
options={editorOptions}
311
className="custom-editor"
312
wrapperProps={{ style: { border: '1px solid #ccc' } }}
313
saveViewState={true}
314
keepCurrentModel={false}
315
/>
316
);
317
}
318
```
319
320
## Model Management
321
322
The editor supports multi-model functionality for working with multiple files or code snippets.
323
324
```typescript { .api }
325
// Model-related props
326
interface ModelProps {
327
/** Path identifies the model - models are cached by path */
328
path?: string;
329
/** Whether to dispose model when component unmounts */
330
keepCurrentModel?: boolean;
331
/** Save editor view state (cursor, scroll) when switching models */
332
saveViewState?: boolean;
333
}
334
```
335
336
**Multi-Model Example:**
337
338
```typescript
339
// File tab editor with model persistence
340
function FileTabEditor() {
341
const [activeFile, setActiveFile] = useState('main.js');
342
343
const files = {
344
'main.js': { language: 'javascript', content: 'console.log("main");' },
345
'utils.ts': { language: 'typescript', content: 'export const util = () => {};' },
346
'styles.css': { language: 'css', content: 'body { margin: 0; }' },
347
};
348
349
return (
350
<div>
351
<div>
352
{Object.keys(files).map(filename => (
353
<button
354
key={filename}
355
onClick={() => setActiveFile(filename)}
356
style={{
357
fontWeight: activeFile === filename ? 'bold' : 'normal'
358
}}
359
>
360
{filename}
361
</button>
362
))}
363
</div>
364
<Editor
365
height="400px"
366
path={activeFile}
367
language={files[activeFile].language}
368
defaultValue={files[activeFile].content}
369
saveViewState={true} // Preserves cursor position per file
370
keepCurrentModel={true} // Keeps models in memory
371
/>
372
</div>
373
);
374
}
375
```