React CodeMirror 2 Wrapper

9.0.1 · maintenance · verified Sun Apr 19

react-codemirror2 is a React component wrapper for CodeMirror 5, designed to embed a customizable code editor into React applications. It provides both `Controlled` and `UnControlled` components, catering to different state management paradigms within React. The current stable version is 9.0.1. Its release cadence is primarily tied to major React version updates for peer dependency compatibility and critical bug fixes, rather than a fixed schedule. A key differentiator is its explicit commitment to CodeMirror 5, meaning it does not support the fundamentally rewritten CodeMirror 6 API. Developers must manually import CodeMirror modes and themes. The library ships with TypeScript types and is widely used for creating syntax-highlighting text areas.

Common errors

Warnings

Install

Imports

Quickstart

Demonstrates a controlled React component wrapping CodeMirror 5, showing how to manage editor state and include necessary CSS and language modes. This setup allows external control over the editor's content.

import React from 'react';
import { Controlled as CodeMirror } from 'react-codemirror2';
import 'codemirror/lib/codemirror.css';
import 'codemirror/theme/material.css';
import 'codemirror/mode/xml/xml';
import 'codemirror/mode/javascript/javascript';

interface MyEditorState {
  value: string;
}

class MyControlledEditor extends React.Component<{}, MyEditorState> {
  constructor(props: {}) {
    super(props);
    this.state = {
      value: '<h1>Hello, controlled CodeMirror!</h1>\n<script>\n  console.log("This is JavaScript");\n</script>',
    };
  }

  render() {
    const options = {
      mode: 'xml',
      theme: 'material',
      lineNumbers: true,
      indentUnit: 2,
      tabSize: 2,
    };

    return (
      <div>
        <p>Edit the code below:</p>
        <CodeMirror
          value={this.state.value}
          options={options}
          onBeforeChange={(editor, data, value) => {
            this.setState({ value });
          }}
          onChange={(editor, data, value) => {
            console.log('Editor value changed:', value);
          }}
        />
      </div>
    );
  }
}

export default MyControlledEditor;

view raw JSON →