Convert Figma logo to code with AI

react-monaco-editor logoreact-monaco-editor

Monaco Editor for React.

4,017
386
4,017
82

Top Related Projects

A browser based code editor

Monaco Editor for React - use the monaco-editor in any React application without needing to use webpack (or rollup/parcel/etc) configuration files / plugins

React Ace Component

CodeMirror 6 component for React. @codemirror https://uiwjs.github.io/react-codemirror/

Codemirror integrated components for React

Quick Overview

The react-monaco-editor project is a React component that provides a wrapper around the Monaco Editor, a powerful code editor developed by Microsoft. It allows developers to easily integrate the Monaco Editor into their React-based applications, enabling features such as syntax highlighting, code completion, and code folding.

Pros

  • Seamless Integration: The react-monaco-editor component makes it easy to integrate the Monaco Editor into a React application, reducing the overhead of setting up the editor from scratch.
  • Feature-rich: The Monaco Editor provides a wide range of features, including syntax highlighting, code completion, code folding, and more, which are all accessible through the react-monaco-editor component.
  • Customizable: The component allows for extensive customization, enabling developers to tailor the editor's appearance and behavior to their specific needs.
  • Cross-platform: The Monaco Editor is a cross-platform solution, and the react-monaco-editor component inherits this capability, making it suitable for a variety of development environments.

Cons

  • Dependency on Monaco Editor: The react-monaco-editor component is heavily dependent on the Monaco Editor, which means that any issues or limitations with the Monaco Editor may also affect the react-monaco-editor component.
  • Potential Performance Impact: Depending on the complexity of the code being edited, the Monaco Editor may have a significant performance impact, especially on lower-powered devices.
  • Limited Documentation: The project's documentation could be more comprehensive, which may make it challenging for new users to get started with the component.
  • Lack of Active Maintenance: The project appears to have a relatively low level of active maintenance, with the last major release being in 2019. This may raise concerns about the long-term viability of the project.

Code Examples

import React from 'react';
import MonacoEditor from 'react-monaco-editor';

const MyEditor = () => {
  const handleEditorDidMount = (editor, monaco) => {
    console.log('editorDidMount', editor);
    editor.focus();
  };

  return (
    <MonacoEditor
      width="100%"
      height="500px"
      language="javascript"
      theme="vs-dark"
      value="// Write your code here"
      options={{
        selectOnLineNumbers: true,
        roundedSelection: false,
        readOnly: false,
        cursorStyle: 'line',
        automaticLayout: false,
      }}
      editorDidMount={handleEditorDidMount}
    />
  );
};

export default MyEditor;

This code example demonstrates how to use the MonacoEditor component to create a simple code editor in a React application. The component is configured with various options, such as the editor's width, height, language, and theme. The handleEditorDidMount function is called when the editor is mounted, allowing you to perform additional setup or customization.

import React, { useState } from 'react';
import MonacoEditor from 'react-monaco-editor';

const MyEditorWithState = () => {
  const [code, setCode] = useState('// Write your code here');

  const handleEditorChange = (newValue) => {
    setCode(newValue);
  };

  return (
    <MonacoEditor
      width="100%"
      height="500px"
      language="javascript"
      theme="vs-dark"
      value={code}
      onChange={handleEditorChange}
      options={{
        selectOnLineNumbers: true,
        roundedSelection: false,
        readOnly: false,
        cursorStyle: 'line',
        automaticLayout: false,
      }}
    />
  );
};

export default MyEditorWithState;

This example demonstrates how to use the MonacoEditor component with state management. The code state variable holds the current value of the editor, and the handleEditorChange function is called whenever the editor's value changes, allowing you to update the state accordingly.

import React from 'react';
import MonacoEditor from 'react-monaco-editor';

const MyEditorWithCustomTheme = () => {
  const handleEditorDidMount = (editor, monaco) => {

Competitor Comparisons

A browser based code editor

Pros of monaco-editor

  • Developed and maintained by Microsoft, ensuring high-quality and regular updates
  • More flexible and can be used with various frameworks or vanilla JavaScript
  • Offers a wider range of features and customization options

Cons of monaco-editor

  • Requires more setup and configuration for use with React applications
  • Steeper learning curve for developers unfamiliar with the Monaco ecosystem
  • Larger bundle size when used without proper optimization

Code Comparison

monaco-editor:

import * as monaco from 'monaco-editor';

monaco.editor.create(document.getElementById('container'), {
  value: 'console.log("Hello, world!")',
  language: 'javascript'
});

react-monaco-editor:

import MonacoEditor from 'react-monaco-editor';

<MonacoEditor
  width="800"
  height="600"
  language="javascript"
  theme="vs-dark"
  value="console.log('Hello, world!')"
  onChange={handleEditorChange}
/>

The monaco-editor provides a more low-level API, allowing for greater flexibility but requiring more setup. In contrast, react-monaco-editor offers a React-specific implementation, simplifying integration into React applications with a more declarative approach.

Monaco Editor for React - use the monaco-editor in any React application without needing to use webpack (or rollup/parcel/etc) configuration files / plugins

Pros of monaco-react

  • More actively maintained with frequent updates
  • Better TypeScript support and type definitions
  • Smaller bundle size and improved performance

Cons of monaco-react

  • Less comprehensive documentation compared to react-monaco-editor
  • Fewer configuration options out of the box
  • Steeper learning curve for beginners

Code Comparison

react-monaco-editor:

import MonacoEditor from 'react-monaco-editor';

<MonacoEditor
  width="800"
  height="600"
  language="javascript"
  theme="vs-dark"
  value={code}
  options={options}
  onChange={handleEditorChange}
/>

monaco-react:

import Editor from '@monaco-editor/react';

<Editor
  height="600px"
  defaultLanguage="javascript"
  defaultValue={code}
  theme="vs-dark"
  options={options}
  onChange={handleEditorChange}
/>

Both libraries provide similar functionality for integrating Monaco Editor into React applications. monaco-react offers a more modern approach with better TypeScript support and performance optimizations. However, react-monaco-editor has been around longer and may have more extensive documentation and examples available. The choice between the two depends on specific project requirements and developer preferences.

React Ace Component

Pros of react-ace

  • Lighter weight and easier to set up compared to Monaco Editor
  • Supports a wider range of programming languages out of the box
  • Better performance for simpler editing tasks

Cons of react-ace

  • Less feature-rich compared to Monaco Editor
  • Limited IntelliSense and advanced code completion capabilities
  • Fewer customization options for themes and editor behavior

Code Comparison

react-ace:

import AceEditor from 'react-ace';

<AceEditor
  mode="javascript"
  theme="monokai"
  onChange={onChange}
  name="UNIQUE_ID_OF_DIV"
  editorProps={{ $blockScrolling: true }}
/>

react-monaco-editor:

import MonacoEditor from 'react-monaco-editor';

<MonacoEditor
  width="800"
  height="600"
  language="javascript"
  theme="vs-dark"
  value={code}
  options={options}
  onChange={onChange}
  editorDidMount={editorDidMount}
/>

Both libraries provide React components for code editing, but react-ace is more lightweight and easier to set up, while react-monaco-editor offers more advanced features and customization options. The choice between them depends on the specific requirements of your project, such as the need for advanced code intelligence or support for a wide range of languages.

CodeMirror 6 component for React. @codemirror https://uiwjs.github.io/react-codemirror/

Pros of react-codemirror

  • Lightweight and faster to load compared to Monaco Editor
  • Easier to customize and extend with plugins
  • Better support for mobile devices and touch screens

Cons of react-codemirror

  • Less feature-rich out of the box compared to Monaco Editor
  • May require more manual configuration for advanced features
  • Smaller community and ecosystem compared to Monaco Editor

Code Comparison

react-monaco-editor:

import MonacoEditor from 'react-monaco-editor';

<MonacoEditor
  width="800"
  height="600"
  language="javascript"
  theme="vs-dark"
  value={code}
  onChange={handleEditorChange}
/>

react-codemirror:

import CodeMirror from '@uiw/react-codemirror';
import { javascript } from '@codemirror/lang-javascript';

<CodeMirror
  value={code}
  height="600px"
  extensions={[javascript()]}
  onChange={handleEditorChange}
  theme="dark"
/>

Both libraries provide React components for code editing, but react-codemirror offers a more lightweight solution with easier customization. react-monaco-editor, based on Monaco Editor, provides a more feature-rich experience out of the box but may be heavier and slower to load. The choice between the two depends on specific project requirements, such as needed features, performance considerations, and target devices.

Codemirror integrated components for React

Pros of react-codemirror2

  • Lighter weight and faster loading compared to Monaco Editor
  • Easier to set up and configure for simple use cases
  • Better support for mobile devices and touch screens

Cons of react-codemirror2

  • Less feature-rich compared to Monaco Editor
  • Limited language support out of the box
  • Fewer advanced editing features like IntelliSense and code refactoring

Code Comparison

react-codemirror2:

import { Controlled as CodeMirror } from 'react-codemirror2';

<CodeMirror
  value={code}
  options={{
    mode: 'javascript',
    theme: 'material',
    lineNumbers: true
  }}
  onBeforeChange={(editor, data, value) => {
    setCode(value);
  }}
/>

react-monaco-editor:

import MonacoEditor from 'react-monaco-editor';

<MonacoEditor
  width="800"
  height="600"
  language="javascript"
  theme="vs-dark"
  value={code}
  options={{
    selectOnLineNumbers: true
  }}
  onChange={(newValue, e) => {
    setCode(newValue);
  }}
/>

Both libraries provide React components for code editing, but react-codemirror2 offers a simpler setup with fewer options, while react-monaco-editor provides more advanced features and configuration options. The choice between them depends on the specific requirements of your project, such as performance needs, desired features, and target devices.

Convert Figma logo designs to code with AI

Visual Copilot

Introducing Visual Copilot: A new AI model to turn Figma designs to high quality code using your components.

Try Visual Copilot

README

react-monaco-editor

Monaco Editor for React.

NPM version Downloads Test

Examples

To build the examples locally, run:

yarn
cd example
yarn
yarn start

Then open http://localhost:8886 in a browser.

Installation

yarn add react-monaco-editor

Using with Webpack

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'],
}

Properties

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).

Events & Methods

Refer to Monaco interface IEditor.

The monaco interfaces available by import

import { monaco } from 'react-monaco-editor';

Q & A

I don't get syntax highlighting / autocomplete / validation.

Make sure to use the Monaco Webpack plugin or follow the instructions on how to load the ESM version of Monaco.

How to interact with the MonacoEditor instance

Using the first parameter of editorDidMount, or using a ref (e.g. <MonacoEditor ref={monacoEditorRef}>).

const monacoEditorRef = useRef(null);
return (<>
  <button onClick={() => monacoEditorRef.current.editor.focus()}>Focus</button>
  <MonacoEditor ref={monacoEditorRef} />
</>)

How to get value of editor

Using this.refs.monaco.editor.getValue() or via method of Model instance:

const model = this.refs.monaco.editor.getModel();
const value = model.getValue();

Do something before editor mounted

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} />
        );
    }
}

Use multiple themes

Monaco only supports one theme.

How to use the diff editor

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}
      />
    );
  }
}

Usage with 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:

  1. Install react-app-rewired: npm install -D react-app-rewired
  2. Replace react-scripts by react-app-rewired in the scripts section of your packages.json
  3. Create a 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.

License

MIT, see the LICENSE file for detail.

NPM DownloadsLast 30 Days