How to do autosuggest css keywords with React Codemirror?

1.7k views Asked by At

I am trying to achieve autosuggestions for css with code mirror browser editor using a react wrapper lib https://www.npmjs.com/package/react-codemirror2

I've tried editor.execCommand('autocomplete'); on onchange event but It crashes the browser

My try

import ReactDOM from "react-dom";
import React from "react";
import {UnControlled as CodeMirror} from 'react-codemirror2';

import 'codemirror/lib/codemirror.css';
import 'codemirror/theme/material.css';
import 'codemirror/addon/hint/show-hint.css';

require('codemirror/mode/css/css');
require('codemirror/addon/hint/css-hint');
require('codemirror/addon/hint/show-hint');
require('codemirror/addon/edit/closebrackets');
require('codemirror/addon/lint/lint');
require('codemirror/addon/display/autorefresh');


const App = () => {

    const handleChange = (editor, data, value) => {

        console.log(editor, data, value);

        /* Crash the browser */
        // editor.execCommand('autocomplete');
    }
    return(
        <div>
            <CodeMirror
                value='body{ background: red }'
                options={{
                    mode: 'css',
                    theme: 'material',
                    lineWrapping: true,
                    smartIndent: true,
                    lineNumbers: true,
                    foldGutter: true,
                    autoCloseTags: true,
                    matchBrackets: true,
                    autoCloseBrackets: true,
                    autoRefresh:true
                }}
                onChange={handleChange}
            />
        </div>
    )
}

const rootElement = document.getElementById("root");
ReactDOM.render(<App />, rootElement);

Thanks in advance

1

There are 1 answers

4
95faf8e76605e973 On

You can use editor.showHint({ completeSingle: false }) instead of editor.execCommand('autocomplete');

const handleChange = (editor, data, value) => {
  editor.showHint({ completeSingle: false });
};

Edit flamboyant-fast-xsdqo


You can also trigger it using certain key combination as described in this Github issue

<CodeMirror
  options={{
    extraKeys: {'Ctrl-Space': 'autocomplete'}, // pressing CTRL + Space will trigger autocomplete
  }}
/>