Security News
Fluent Assertions Faces Backlash After Abandoning Open Source Licensing
Fluent Assertions is facing backlash after dropping the Apache license for a commercial model, leaving users blindsided and questioning contributor rights.
react-monaco-editor
Advanced tools
The react-monaco-editor package is a React component for integrating the Monaco Editor, which is the code editor that powers Visual Studio Code, into React applications. It provides a rich set of features for code editing, including syntax highlighting, IntelliSense, and more.
Basic Usage
This code demonstrates the basic usage of the react-monaco-editor package. It sets up a Monaco Editor instance with JavaScript syntax highlighting and a dark theme. The editor's content is managed via the component's state.
import React from 'react';
import MonacoEditor from 'react-monaco-editor';
class MyEditor extends React.Component {
constructor(props) {
super(props);
this.state = {
code: '// type your code...'
};
}
editorDidMount(editor, monaco) {
console.log('editorDidMount', editor);
editor.focus();
}
onChange(newValue, e) {
console.log('onChange', newValue, e);
this.setState({ code: newValue });
}
render() {
const code = this.state.code;
const options = {
selectOnLineNumbers: true
};
return (
<MonacoEditor
width="800"
height="600"
language="javascript"
theme="vs-dark"
value={code}
options={options}
onChange={this.onChange.bind(this)}
editorDidMount={this.editorDidMount.bind(this)}
/>
);
}
}
export default MyEditor;
Customizing Editor Options
This example shows how to customize the editor options, such as making the editor read-only and disabling the minimap. The editor is set to use a light theme and displays some read-only code.
import React from 'react';
import MonacoEditor from 'react-monaco-editor';
class CustomEditor extends React.Component {
render() {
const options = {
selectOnLineNumbers: true,
readOnly: true,
minimap: { enabled: false }
};
return (
<MonacoEditor
width="800"
height="600"
language="javascript"
theme="vs-light"
value={'// read-only code'}
options={options}
/>
);
}
}
export default CustomEditor;
Handling Editor Events
This example demonstrates how to handle editor events, such as cursor position changes. The editorDidMount method is used to attach an event listener to the editor instance.
import React from 'react';
import MonacoEditor from 'react-monaco-editor';
class EventHandlingEditor extends React.Component {
editorDidMount(editor, monaco) {
editor.onDidChangeCursorPosition((e) => {
console.log('Cursor position changed:', e.position);
});
}
render() {
return (
<MonacoEditor
width="800"
height="600"
language="javascript"
theme="vs-dark"
value={'// type your code...'}
editorDidMount={this.editorDidMount.bind(this)}
/>
);
}
}
export default EventHandlingEditor;
react-ace is a React component for the Ace editor, another popular code editor. It offers similar features like syntax highlighting, themes, and language support. However, Monaco Editor is generally considered more powerful and feature-rich, especially for larger projects.
react-codemirror2 is a React component for the CodeMirror editor. CodeMirror is known for its flexibility and is highly customizable. While it offers many of the same features as Monaco Editor, it may require more configuration to achieve similar functionality.
react-simple-code-editor is a lightweight code editor component for React. It is built on top of the Prism syntax highlighter and is designed for simplicity and ease of use. It lacks some of the advanced features of Monaco Editor, such as IntelliSense and extensive language support.
Monaco Editor for React.
To build the examples locally, run:
yarn
cd example
yarn
yarn start
Then open http://localhost:8886
in a browser.
yarn add react-monaco-editor
import React from 'react';
import { createRoot } from "react-dom/client";
import MonacoEditor from 'react-monaco-editor';
class App extends React.Component {
constructor(props) {
super(props);
this.state = {
code: '// type your code...',
}
}
editorDidMount(editor, monaco) {
console.log('editorDidMount', editor);
editor.focus();
}
onChange(newValue, e) {
console.log('onChange', newValue, e);
}
render() {
const code = this.state.code;
const options = {
selectOnLineNumbers: true
};
return (
<MonacoEditor
width="800"
height="600"
language="javascript"
theme="vs-dark"
value={code}
options={options}
onChange={::this.onChange}
editorDidMount={::this.editorDidMount}
/>
);
}
}
const container = document.getElementById('root');
const root = createRoot(container);
root.render(<App />);
Add the Monaco Webpack plugin monaco-editor-webpack-plugin
to your webpack.config.js
:
const MonacoWebpackPlugin = require('monaco-editor-webpack-plugin');
module.exports = {
plugins: [
new MonacoWebpackPlugin({
// available options are documented at https://github.com/microsoft/monaco-editor/blob/main/webpack-plugin/README.md#options
languages: ['json']
})
]
};
Sidenote: Monaco Editor uses CSS imports internally, so if you're using CSS Modules in your project - you're likely to get conflict by default. In order to avoid that - separate css-loader for app and monaco-editor package:
// Specify separate paths
const path = require('path');
const APP_DIR = path.resolve(__dirname, './src');
const MONACO_DIR = path.resolve(__dirname, './node_modules/monaco-editor');
{
test: /\.css$/,
include: APP_DIR,
use: [{
loader: 'style-loader',
}, {
loader: 'css-loader',
options: {
modules: true,
namedExport: true,
},
}],
}, {
test: /\.css$/,
include: MONACO_DIR,
use: ['style-loader', 'css-loader'],
}
All the properties below are optional.
width
width of editor. Defaults to 100%
.
height
height of editor. Defaults to 100%
.
value
value of the auto created model in the editor.
defaultValue
the initial value of the auto created model in the editor.
language
the initial language of the auto created model in the editor.
theme
the theme of the editor
options
refer to Monaco interface IStandaloneEditorConstructionOptions.
overrideServices
refer to Monaco Interface IEditorOverrideServices. It depends on Monaco's internal implementations and may change over time, check github issue for more details.
onChange(newValue, event)
an event emitted when the content of the current model has changed.
editorWillMount(monaco)
an event emitted before the editor mounted (similar to componentWillMount
of React).
editorDidMount(editor, monaco)
an event emitted when the editor has been mounted (similar to componentDidMount
of React).
editorWillUnmount(editor, monaco)
an event emitted before the editor unmount (similar to componentWillUnmount
of React).
Refer to Monaco interface IEditor.
The monaco interfaces available by import
import { monaco } from 'react-monaco-editor';
Make sure to use the Monaco Webpack plugin or follow the instructions on how to load the ESM version of Monaco.
Using the first parameter of editorDidMount
, or using a ref
(e.g. <MonacoEditor ref="monaco">
) after editorDidMount
event has fired.
Then you can invoke instance methods via this.refs.monaco.editor
, e.g. this.refs.monaco.editor.focus()
to focuses the MonacoEditor instance.
Using this.refs.monaco.editor.getValue()
or via method of Model
instance:
const model = this.refs.monaco.editor.getModel();
const value = model.getValue();
For example, you may want to configure some JSON schemas before editor mounted, then you can go with editorWillMount(monaco)
:
class App extends React.Component {
editorWillMount(monaco) {
monaco.languages.json.jsonDefaults.setDiagnosticsOptions({
validate: true,
schemas: [{
uri: "http://myserver/foo-schema.json",
fileMatch: ['*'],
schema: {
type: "object",
properties: {
p1: {
enum: [ "v1", "v2"]
},
p2: {
$ref: "http://myserver/bar-schema.json"
}
}
}
}]
});
}
render() {
return (
<MonacoEditor language="json" editorWillMount={this.editorWillMount} />
);
}
}
Monaco only supports one theme.
import React from 'react';
import { MonacoDiffEditor } from 'react-monaco-editor';
class App extends React.Component {
render() {
const code1 = "// your original code...";
const code2 = "// a different version...";
const options = {
//renderSideBySide: false
};
return (
<MonacoDiffEditor
width="800"
height="600"
language="javascript"
original={code1}
value={code2}
options={options}
/>
);
}
}
create-react-app
The easiest way to use the react-monaco-editor
with create-react-app
is to use the react-app-rewired project. For setting it up, the following steps are required:
react-app-rewired
: npm install -D react-app-rewired
react-scripts
by react-app-rewired
in the scripts section of your packages.json
config-overrides.js
in the root directory of your project with the following content:const MonacoWebpackPlugin = require('monaco-editor-webpack-plugin');
module.exports = function override(config, env) {
config.plugins.push(new MonacoWebpackPlugin({
languages: ['json']
}));
return config;
}
For more information checkout the documentation of react-app-rewired
here.
MIT, see the LICENSE file for detail.
FAQs
Monaco Editor for React
The npm package react-monaco-editor receives a total of 100,532 weekly downloads. As such, react-monaco-editor popularity was classified as popular.
We found that react-monaco-editor demonstrated a healthy version release cadence and project activity because the last version was released less than a year ago. It has 3 open source maintainers collaborating on the project.
Did you know?
Socket for GitHub automatically highlights issues in each pull request and monitors the health of all your open source dependencies. Discover the contents of your packages and block harmful activity before you install or update your dependencies.
Security News
Fluent Assertions is facing backlash after dropping the Apache license for a commercial model, leaving users blindsided and questioning contributor rights.
Research
Security News
Socket researchers uncover the risks of a malicious Python package targeting Discord developers.
Security News
The UK is proposing a bold ban on ransomware payments by public entities to disrupt cybercrime, protect critical services, and lead global cybersecurity efforts.