how to use codemirror autocomplete from a react js app

I need to add a full Javascript code editor on my React App, which is using React Boilerplate and Dandelion template. I have installed react-codemirror2 as instructed on https://www.npmjs.com/package/react-codemirror2. I have this component:

import React from 'react';

import { Controlled as CodeMirror } from 'react-codemirror2';
import 'codemirror/lib/codemirror.css';
import 'codemirror/theme/material.css';
import 'codemirror/mode/javascript/javascript';
import 'codemirror/addon/hint/show-hint';
import 'codemirror/addon/hint/javascript-hint';
import 'codemirror/addon/hint/show-hint.css';
import 'codemirror/addon/hint/anyword-hint';
import 'codemirror/keymap/sublime';
import 'codemirror/addon/edit/closebrackets';
import 'codemirror/addon/edit/closetag';
import 'codemirror/addon/fold/foldcode';
import 'codemirror/addon/fold/foldgutter';
import 'codemirror/addon/fold/brace-fold';
import 'codemirror/addon/fold/comment-fold';
import 'codemirror/addon/fold/foldgutter.css';

function CodeEditor() {
  const [code, setCode] = React.useState('// my code goes here');

  return (
    <CodeMirror
      value={code}
      options={{
        mode: 'javascript',
        lineWrapping: true,
        smartIndent: true,
        lineNumbers: true,
        foldGutter: true,
        gutters: ['CodeMirror-linenumbers', 'CodeMirror-foldgutter'],
        autoCloseTags: true,
        keyMap: 'sublime',
        matchBrackets: true,
        autoCloseBrackets: true,
        extraKeys: {
          'Ctrl-Space': 'autocomplete'
        }
      }}
      onBeforeChange={(editor, data, value) => {
        setCode(value);
      }}
      onChange={(editor, data, value) => {}}
    />
  );
}

export default CodeEditor;

which is the same as in https://codesandbox.io/s/clever-shape-20y39?file=/src/App.js, but, in the sandbox the autocomplete shows up, and the same code snippet does not shows the autocomplete in the react app. What am I missing here?

2 Likes

Hi,

Adding below code in OnBeforeChange fixed the issue:
editor.showHint({ completeSingle: false });

I know this was posted long back, but hope this helps someone.