Search code examples
reactjscodemirrorcodemirror-modesreact-codemirror

How to use custom CodeMirror modes using react-codemirror2


How do you use custom CodeMirror modes when using react-codemirror2? Both CodeMirror.defineSimpleMode and CodeMirror.defineMode are undefined after I import as follows:

import {UnControlled as CodeMirror} from "react-codemirror2";
import 'codemirror/lib/codemirror.css';

Context: In my react project I'd like to use CodeMirror and define my own input language which matches against some regex's and then highlights them to indicate the user has entered them correctly. I also want line numbers, no wrapping, monospace fonts, therefore a code editor seems close to what I want to achieve.


Solution

  • You have two options to use custom modes using react-codemirror2.

    1. Use the defineMode prop and pass in the mode and its function:
    import { UnControlled as CodeMirror } from "react-codemirror2";
    import 'codemirror/lib/codemirror.css';
    
    <CodeMirror
      options={{
        lineNumbers: true,
        defineMode: {
          name: 'yourMode',
          fn: yourModeFunction
        },
        ...
    
      }}
      ...
    />;
    
    1. Separately import CodeMirror and define your mode before the control is rendered:
    import { UnControlled as CodeMirrorControl } from "react-codemirror2";
    import 'codemirror/lib/codemirror.css';
    import CodeMirror from 'codemirror';
    
    CodeMirror.defineMode('yourMode', yourModeFunction);
    
    <CodeMirrorControl
      options={{
        lineNumbers: true,
        ...
        mode: 'yourMode',
      }}
      ...
    />;