0
# Monaco Editor
1
2
The MonacoEditor component provides full Monaco Editor functionality as a React component, supporting both controlled and uncontrolled modes with complete lifecycle management.
3
4
## Capabilities
5
6
### Monaco Editor Component
7
8
React component wrapper for Monaco Editor with full TypeScript support and lifecycle management.
9
10
```typescript { .api }
11
/**
12
* Monaco Editor React component
13
* @param props - MonacoEditorProps configuration
14
* @param ref - Forward ref to access editor instance
15
* @returns React element containing Monaco Editor
16
*/
17
declare const MonacoEditor: React.ForwardRefExoticComponent<
18
MonacoEditorProps & React.RefAttributes<MonacoEditorHandle>
19
>;
20
```
21
22
**Usage Examples:**
23
24
```typescript
25
import React, { useRef, useState } from "react";
26
import MonacoEditor from "react-monaco-editor";
27
28
// Controlled mode with state
29
function ControlledEditor() {
30
const [code, setCode] = useState('console.log("Hello World");');
31
32
return (
33
<MonacoEditor
34
height="400"
35
language="javascript"
36
theme="vs-dark"
37
value={code}
38
onChange={(newValue) => setCode(newValue)}
39
options={{
40
selectOnLineNumbers: true,
41
minimap: { enabled: false },
42
fontSize: 14,
43
}}
44
/>
45
);
46
}
47
48
// Uncontrolled mode with ref access
49
function UncontrolledEditor() {
50
const editorRef = useRef<{ editor: monaco.editor.IStandaloneCodeEditor }>(null);
51
52
const getValue = () => {
53
if (editorRef.current) {
54
const value = editorRef.current.editor.getValue();
55
console.log(value);
56
}
57
};
58
59
return (
60
<div>
61
<button onClick={getValue}>Get Value</button>
62
<MonacoEditor
63
ref={editorRef}
64
height="400"
65
language="typescript"
66
defaultValue="// Default content"
67
editorDidMount={(editor, monaco) => {
68
editor.focus();
69
console.log('Editor mounted');
70
}}
71
/>
72
</div>
73
);
74
}
75
```
76
77
### Component Props
78
79
Full configuration interface for the Monaco Editor component.
80
81
```typescript { .api }
82
interface MonacoEditorProps extends MonacoEditorBaseProps {
83
/** Value of the auto created model in the editor.
84
* If you specify `null` or `undefined` for this property, the component behaves in uncontrolled mode.
85
* Otherwise, it behaves in controlled mode. */
86
value?: string | null;
87
88
/** Refer to Monaco interface {monaco.editor.IStandaloneEditorConstructionOptions}. */
89
options?: monaco.editor.IStandaloneEditorConstructionOptions;
90
91
/** Refer to Monaco interface {monaco.editor.IEditorOverrideServices}. */
92
overrideServices?: monaco.editor.IEditorOverrideServices;
93
94
/** An event emitted before the editor mounted (similar to componentWillMount of React). */
95
editorWillMount?: EditorWillMount;
96
97
/** An event emitted when the editor has been mounted (similar to componentDidMount of React). */
98
editorDidMount?: EditorDidMount;
99
100
/** An event emitted before the editor unmount (similar to componentWillUnmount of React). */
101
editorWillUnmount?: EditorWillUnmount;
102
103
/** An event emitted when the content of the current model has changed. */
104
onChange?: ChangeHandler;
105
106
/** Let the language be inferred from the uri */
107
uri?: (monaco: typeof monaco) => monaco.Uri;
108
}
109
```
110
111
### Editor Handle
112
113
Interface for accessing the Monaco Editor instance via React ref.
114
115
```typescript { .api }
116
interface MonacoEditorHandle {
117
/** Direct access to Monaco editor instance */
118
editor: monaco.editor.IStandaloneCodeEditor;
119
}
120
```
121
122
**Usage Example:**
123
124
```typescript
125
import React, { useRef } from "react";
126
import MonacoEditor from "react-monaco-editor";
127
128
function EditorWithRef() {
129
const editorRef = useRef<MonacoEditorHandle>(null);
130
131
const insertText = () => {
132
if (editorRef.current) {
133
const editor = editorRef.current.editor;
134
const position = editor.getPosition();
135
editor.executeEdits("my-source", [{
136
range: new monaco.Range(position.lineNumber, position.column, position.lineNumber, position.column),
137
text: "Hello World!"
138
}]);
139
}
140
};
141
142
return (
143
<div>
144
<button onClick={insertText}>Insert Text</button>
145
<MonacoEditor
146
ref={editorRef}
147
height="400"
148
language="javascript"
149
defaultValue="// Click button to insert text"
150
/>
151
</div>
152
);
153
}
154
```
155
156
### Lifecycle Callbacks
157
158
Callback functions for handling editor lifecycle events.
159
160
```typescript { .api }
161
/**
162
* Callback invoked before the editor is mounted
163
* @param monaco - Monaco Editor API instance
164
* @returns Optional editor construction options to merge with props.options
165
*/
166
type EditorWillMount = (
167
monaco: typeof monaco
168
) => void | EditorConstructionOptions;
169
170
/**
171
* Callback invoked after the editor has been mounted
172
* @param editor - The mounted Monaco editor instance
173
* @param monaco - Monaco Editor API instance
174
*/
175
type EditorDidMount = (
176
editor: monaco.editor.IStandaloneCodeEditor,
177
monaco: typeof monaco
178
) => void;
179
180
/**
181
* Callback invoked before the editor is unmounted
182
* @param editor - The Monaco editor instance being unmounted
183
* @param monaco - Monaco Editor API instance
184
*/
185
type EditorWillUnmount = (
186
editor: monaco.editor.IStandaloneCodeEditor,
187
monaco: typeof monaco
188
) => void | EditorConstructionOptions;
189
190
/**
191
* Callback invoked when editor content changes
192
* @param value - The new editor content
193
* @param event - Monaco editor content change event
194
*/
195
type ChangeHandler = (
196
value: string,
197
event: monaco.editor.IModelContentChangedEvent
198
) => void;
199
```
200
201
**Usage Example:**
202
203
```typescript
204
function EditorWithLifecycle() {
205
const editorWillMount = (monaco) => {
206
// Configure JSON schemas before editor mounts
207
monaco.languages.json.jsonDefaults.setDiagnosticsOptions({
208
validate: true,
209
schemas: [{
210
uri: "http://myserver/foo-schema.json",
211
fileMatch: ['*'],
212
schema: {
213
type: "object",
214
properties: {
215
name: { type: "string" },
216
version: { type: "string" }
217
}
218
}
219
}]
220
});
221
};
222
223
const editorDidMount = (editor, monaco) => {
224
console.log('Editor mounted');
225
editor.focus();
226
227
// Add custom command
228
editor.addCommand(monaco.KeyMod.CtrlCmd | monaco.KeyCode.KeyS, () => {
229
console.log('Save command triggered');
230
});
231
};
232
233
const editorWillUnmount = (editor, monaco) => {
234
console.log('Editor will unmount');
235
// Cleanup custom resources if needed
236
};
237
238
const onChange = (newValue, event) => {
239
console.log('Content changed:', newValue);
240
console.log('Change event:', event);
241
};
242
243
return (
244
<MonacoEditor
245
height="400"
246
language="json"
247
defaultValue='{"name": "example"}'
248
editorWillMount={editorWillMount}
249
editorDidMount={editorDidMount}
250
editorWillUnmount={editorWillUnmount}
251
onChange={onChange}
252
/>
253
);
254
}
255
```
256
257
### URI Support
258
259
Custom URI creation for Monaco models, useful for language services and validation.
260
261
```typescript { .api }
262
/**
263
* Function to create a Monaco URI for the editor model
264
* @param monaco - Monaco Editor API instance
265
* @returns Monaco URI for the model
266
*/
267
uri?: (monaco: typeof monaco) => monaco.Uri;
268
```
269
270
**Usage Example:**
271
272
```typescript
273
function EditorWithURI() {
274
return (
275
<MonacoEditor
276
height="400"
277
language="typescript"
278
defaultValue="interface User { name: string; }"
279
uri={(monaco) => monaco.Uri.parse("file:///user-types.ts")}
280
/>
281
);
282
}
283
```
284
285
### Common Options
286
287
Frequently used Monaco Editor configuration options:
288
289
```typescript
290
const commonOptions = {
291
// Line numbers
292
lineNumbers: 'on' as const,
293
lineNumbersMinChars: 3,
294
295
// Code folding
296
folding: true,
297
foldingStrategy: 'auto' as const,
298
299
// Minimap
300
minimap: { enabled: true },
301
302
// Font and rendering
303
fontSize: 14,
304
fontFamily: 'Monaco, Menlo, "Ubuntu Mono", monospace',
305
renderWhitespace: 'selection' as const,
306
307
// Selection and cursor
308
selectOnLineNumbers: true,
309
roundedSelection: false,
310
cursorStyle: 'line' as const,
311
312
// Layout
313
automaticLayout: true,
314
scrollBeyondLastLine: false,
315
316
// Editing behavior
317
wordWrap: 'off' as const,
318
readOnly: false,
319
};
320
```